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
在獲取只有一個單詞的行後沒有更新。
請向我解釋這一點,我不想正確的答案與代碼,我想知道爲什麼。
謝謝。
SS已經遇到過eof,所以你需要在重新使用之前重置標誌。看看這個http://stackoverflow.com/questions/2848087/how-to-clear-stringstream – Carth