在分隔逗号时使用 getline() 不起作用
using getline() while separating comma didn't work
我读取了一个 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()
returnstrue
).
要么在 while
循环中使用局部变量:
while (getline(content,var,'\r'))
{
stringstream ss(var);
或清空ss.str
前的流:
ss.clear();
ss.str(var);
我读取了一个 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()
returnstrue
).
要么在 while
循环中使用局部变量:
while (getline(content,var,'\r'))
{
stringstream ss(var);
或清空ss.str
前的流:
ss.clear();
ss.str(var);