許多博客都有提到stringstream的清空,不應該調用clear,而是要調用str(""),傳入一個空字符串來讓其清空內容。
然而我將提到的是clear的真正用法,究竟什么情況下需要用到clear
先來看一個stack overflow上的問題(http://stackoverflow.com/questions/35080342/using-two-string-streams-but-not-getting-same-result)
我將其簡化為以下代碼:
int main()
{
string line = "1 2 3 4 5";
stringstream s1(line);
string temp;
int toAdd;
stringstream s2;
while (s1 >> temp)
{
cout << "temp:" << temp << endl;
s2 << temp;
cout << "s2.str: " << s2.str() << endl;
s2 >> toAdd;
cout << "toAdd:" << toAdd << endl;
s2.str("");
}
return 0;
}
這個代碼的原意是要把line中的字符串形式的1 2 3 4 5一個一個地轉成int並輸出,所以我們期望的toAdd的輸出應該是1 2 3 4 5,但結果卻是 1 1 1 1 1, 如下圖
可以從s2.str:這句輸出中看到, 只有第一次是正常地把temp輸入進s2,后面的都失敗了。
原因在於, s2在第一次調用完operator<<和operator>>后,來到了end-of-file的位置,此時stringstream會為其設置一個eofbit的標記位,標記其為已經到達eof。查文檔得知, 當stringstream設置了eofbit,任何讀取eof的操作都會失敗,同時,會設置failbit的標記位,標記為失敗狀態。所以后面的操作都失敗了,toAdd的值一直都是1。
Operations that attempt to read at the End-of-File fail, and thus both the eofbit and the failbit end up set. This function can be used to check whether the failure is due to reaching the End-of-File or to some other reason.
clear函數:
原型: void clear (iostate state = goodbit);
標志位一共有4種, goodbit, eofbit, failbit, badbit
clear可以清除掉所有的error state
int main()
{
string line = "1 2 3 4 5";
stringstream s1(line);
string temp;
int toAdd;
stringstream s2;
while (s1 >> temp)
{
cout << "temp:" << temp << endl;
s2 << temp;
cout << "s2.str: " << s2.str() << endl;
s2 >> toAdd;
cout << "toAdd:" << toAdd << endl;
s2.str("");
if (s2.eof())
{
s2.clear();
cout << "s2.eof true" << endl;
}
}
return 0;
}
使用clear后, s2就可以正常地工作了,結果如下:

參考網站:http://www.cplusplus.com/reference/sstream/stringstream/
http://www.cplusplus.com/reference/ios/ios/clear/
