c++ - 在分隔逗号时使用 getline() 不起作用

标签 c++ csv getline

我读取了一个 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/

相关文章:

c++ - 使用模板管理 glUniform 函数

c++ - 使用宏进行赋值和错误检查

python - 将从 HTML 表中抓取的数据写入 CSV 文件

c++ - 防止在基类和派生类上使用 delete,同时允许使用 new

c++ - 与普通 POD 类型相比,如何克服仅包含一个 POD 成员的简单类的性能下降?

c++ - 在 C++ 中使用两个 getline(cin,s)

c++ - 在 C++ 中将 getline() 与文件输入一起使用

Cin 之后的 C++ Getline

php - Laravel 验证器和 excel 文件错误

python - 使用 Geopy 和 Python 进行地理编码