2015-12-21 80 views
0

我已经读取了一个以'\ r'结尾的字符作为'\ r'的CSV文件,读取操作成功完成,但是当我将读取的行传递给while(getline(ss,arr2,','))用于分隔逗号..它为第一行工作正常,但所有下一次迭代都是空的(即)它一直未能分隔字符串中的逗号。使用getline()时分隔逗号不起作用

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(); 
} 

在什么上面了错误...我什么也看不到,现在:(

+1

使用本地'字符串流SS;'while循环或'ss.clear内()'重置流状态 –

+0

@DieterLücking,只是出于好奇没有按ss.str(“”)清除流? –

+0

@DieterLücking,That worked :) –

回答

2

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

既可以使用while循环内的局部变量:

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

或清除流之前ss.str

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

非常感谢Worked :) –