2013-05-19 26 views
0

我具有例如這樣的代碼:stringstream的古怪行爲字符串用一個字後

#include <iostream> 
#include <sstream> 

using namespace std; 
int main(){ 
    stringstream ss; 
    string buffer,first_word; 
    int i; 
    for(i = 0; i < 4; i++){ 
     getline(cin,buffer); // getting line 
     ss.str(buffer);   // initializing the stream 
     ss>>first_word; 
     cout<<first_word<<endl; 
     ss.str(string());  // cleaning stream 
    } 
    return 0; 
} 

與該輸入:

line one with spaces 
line two with spaces 
alone 
line four with spaces 

我期望的輸出只是線的第一個詞,像這樣的:

line 
line 
alone 
line 

但我得到這個:

line 
line 
alone 
alone 

因此,stringstream在獲取只有一個單詞的行後沒有更新。

請向我解釋這一點,我不想正確的答案與代碼,我想知道爲什麼。

謝謝。

+0

SS已經遇到過eof,所以你需要在重新使用之前重置標誌。看看這個http://stackoverflow.com/questions/2848087/how-to-clear-stringstream – Carth

回答

1

如果你懶得去檢查流的狀態,你會看到這樣一行:

ss>>first_word; 
    if (!ss.good()) std::cout << "problem." << std::endl; 
    cout<<first_word<<endl; 

確實輸出「的問題。」

ss.str(""); 
    ss.clear(); 

解決了這個問題。