2015-07-19 87 views
0

我有這樣的代碼,關於stringstream。我發現了一個奇怪的現象:爲什麼stringstream有這種行爲?

#include <iostream> 
#include <fstream> 
#include <sstream> 

using namespace std; 

int main() 
{ 
    int  p, q; 
    fstream file; 
    string str; 
    stringstream sstr; 

    file.open("file.txt", ios::in); 
    if(file.is_open()) { 
    while(getline(file, str)) { 
     sstr << str; 
     sstr >> p >> q; 
     cout << p << ' ' << q << endl; 
     sstr.str(""); 
    } 
    } 
    file.close(); 

    return 0; 
} 

假設我有FILE.TXT作爲

4 5 

0 2 

在第一行第二行5後回報和2。該計劃給了我:

4 5 

4 5 

這意味着pq分配不正確。但我檢查了每次sstr.str()與獲得正確的線的字符串。

爲什麼stringstream有這樣的行爲?

+0

什麼是預期的輸出呢? – Shoe

+1

[如何清除stringstream?](http://stackoverflow.com/questions/2848087/how-to-clear-stringstream)解決你的問題? – Lithis

回答

3

讀取第二個整數後,流處於非良好狀態,因此您必須在恢復之前重置其錯誤狀態。

你真正的錯誤是不檢查輸入操作的返回值,或者你立刻就會發現這個錯誤!


更簡單的解決方案可能是不嘗試重用相同的流,而是讓它重新每輪:

for (std::string line; std::getline(file, line);) 
{ 
    std::istringstream iss(line); 
    if (!(iss >> p >> q >> std::ws) || !iss.eof()) 
    { 
     // parse error! 
     continue; 
    } 
    std::cout << "Input: [" << p << ", " << q << "]\n"; 
} 
+0

[Demo](https://ideone.com/piHs07)。 –

1

當你閱讀p,然後q,到達後,你的流和國旗eofbit已設置,你不能再做任何事情。 只需clear()它和您的代碼將按預期工作。

但是你可能需要使用直接file,而是和file.close();將有中更好的地方您if

fstream file; 
file.open("file.txt", ios::in); 
if(file.is_open()) { 
    int p, q; 
    while(file >> p >> q) { 
    cout << p << ' ' << q << endl; 
    } 
    file.close(); 
} 
0

您的代碼具有一定的冗餘線路:fstream可以在定義的過程中被打開,沒有明確的文件需要close(),因爲它在main()結束時自動銷燬。

此外,在文件讀取循環,行:sstr.str("");冗餘以及:sstr << str應與stringstream sstr(line);,如果你想初始化每行一個新的stringstream,這將使線路取代。

應用上述更正,這裏是你的代碼:

int main() { 

    int p, q; 
    fstream file("file.txt", ios::in); 

    // check status 
    if (!file) cerr << "Can't open input file!\n"; 

    string line; 

    // read all the lines in the file 
    while(getline(file, line)) { 

     // initialize the stringstream with line 
     stringstream sstr(line); 

     // extract line contents (see Note) 
     while (sstr >> p >> q) { 

      // print extracted integers to standard output 
      cout <<"p: " << p <<" q: "<< q << endl; 
     } 
    } 

    return 0; 
} 

注:該生產線while (sstr >> p >> q)假定一個行只包含整數,用空格分隔。

相關問題