我读取了一个 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();
}
上面哪里出了问题...我现在什么都没看到:(
最佳答案
stringstream::str
方法不会重置/清除流的内部状态。第一行之后,ss
的内部状态为EOF
(ss.eof()
返回true
)。
在 while
循环中使用局部变量:
while (getline(content,var,'\r'))
{
stringstream ss(var);
或者清除ss.str
之前的流:
ss.clear();
ss.str(var);
关于c++ - 在分隔逗号时使用 getline() 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34392880/