【发布时间】:2016-03-27 08:41:36
【问题描述】:
我已经读取了一个 CSV 文件,它的行结束字符为“\r”,读取操作成功完成,但是当我将读取的行传递给 while(getline(ss,arr2,',')) 以分隔逗号时,问题就开始了。它确实有效第一行正确,但所有下一次迭代都是空的(即)它未能分隔字符串中的逗号。
int main()
{
cout<<"Enter the file path :";
string filename;
cin>>filename;
ifstream file;
vector<string>arr;
string line,var;
stringstream content;
file.open(filename.c_str(),ios::in );
line.assign((std::istreambuf_iterator<char>(file)),
std::istreambuf_iterator<char>());
file.close();
string arr2;
stringstream ss;
content<<line;
//sqlite3 *db;int rc;sqlite3_stmt * stmt;
int i=0;
while (getline(content,var,'\r'))
{
ss.str(var);//for each read the ss contains single line which i could print it out.
cout<<ss.str()<<endl;
while(getline(ss,arr2,','))//here the first line is neatly separated and pushed into vector but it fail to separate second and further lines i was really puzzled about this behaviour.
{
arr.push_back(arr2);
}
ss.str("");
var="";
arr2="";
for(int i=0;i<arr.size();i++)
{
cout<<arr[i]<<endl;
}
arr.clear();
}
getch();
}
上面出了什么问题...我现在什么也没看到:(
【问题讨论】:
-
在 while 循环中使用本地
stringstream ss;或ss.clear()重置流状态 -
@DieterLücking,只是出于好奇, ss.str("") 不会清除流吗?
-
@DieterLücking,这工作:)
-
@RichardGeorge
ss.str("")清除流的内容,而不是其状态。