2015-12-21 99 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 :) –