如何从文件中读取数据,如果我的文件是这样的用逗号分隔值用逗号分隔值
1, 2, 3, 4, 5\n
6, 7, 8, 9, 10\n
\n
和读取文件后,我要如何读取写入/从文本文件将数据以上面相同的格式写回到其他文件中。
我可以得到线的总数量,使用
string line;
while(!file.eof()){
getline(file,line);
numlines++;
}
numline--; // remove the last empty line
,但我怎么能知道行/线总的数字位数?
我也有整数矢量来存储数据。 因此,我想读取第一行,然后计算该行中的元素总数,这里是5(1,2,3,4,5),并将它们存储在数组/矢量中,然后读取下一行并将它们存储在再次导航,直到我到达EOF。
然后,我想将数据写入到文件,再次,我想这会做将数据写入到文件的工作,
numOfCols=1;
for(int i = 0; i < vector.size(); i++)
{
file << vector.at(i);
if((numOfCols<5) file << ",";//print comma (,)
if((i+1)%5==0)
{
file << endl;//print newline after 5th value
numOfCols=1;//start from column 1 again, for the next line
}
numOfCols++;
}
file << endl;// last new line
所以,我的主要问题是如何从文件中读取数据用逗号分隔值
感谢
这是干什么的? std :: stringstream linestream(line); – Curious 2009-09-25 00:38:15
它创建一个字符串流对象。它的行为与std :: cin,std :: cout或std :: fstream文件流类似,但使用字符串作为数据源。所以实际上它只是一条线的流。 – 2009-09-25 00:44:51
当我尝试编译时,出现这个错误,变量'std :: stringstream linestream'有初始值设定项但是不完整的类型。 我已经包含了所有需要的头文件。 – Curious 2009-09-25 01:11:03