【问题标题】:using getline() while separating comma didn't work在分隔逗号时使用 getline() 不起作用
【发布时间】: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("") 清除流的内容,而不是其状态。

标签: c++ csv getline


【解决方案1】:

stringstream::str 方法不会重置/清除流的内部状态。在第一行之后,ss 的内部状态为EOF(ss.eof() 返回true)。

在while 循环中使用局部变量:

while (getline(content,var,'\r'))
{
    stringstream ss(var);

或者清除ss.str之前的流:

ss.clear();
ss.str(var);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-01-23
    • 2013-10-07
    • 1970-01-01
    • 1970-01-01
    • 2016-05-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多