我有下面的代碼兩次結束了,我不明白爲什麼結果恰好是像下面這樣:COUT一個字符串流中損壞COUT(小例子)
#include <iostream>
#include <sstream>
using namespace std;
int main() {
std::stringstream s;
std::streambuf *backup;
backup = cout.rdbuf();
s << "Oh my god" << endl;
cout << "Before1" << endl;
cout << s.rdbuf();
cout << "After1" << endl;
cout << "Before2" << endl;
//s.seekg(0, std::ios_base::beg); // If that is in: After 2 is printed!
cout << s.rdbuf();
//cout.rdbuf(backup); // If that is in, also After 2 is printed!
cout << "After2" << endl;
}
輸出:
Before1
Oh my god
After1
Before2
其餘的地方??只有當我們取消註釋上述行時才輸出... 內部會發生什麼?有人知道嗎? =)會很有趣......
這可能是它的的libstdC++文檔已經這樣說了'__ostream_type& 運營商<<(__ streambuf_type * __sb);' 「如果函數沒有插入字符,failbit設置。」這看起來似乎是合理的,因爲's.rdbuf()'會在第二次嘗試打印時結束。 – nos 2012-07-11 21:42:09
哦,謝謝!這就是要點!我們可以在libstdC++ docu中讀取哪些內容? – Gabriel 2012-07-11 21:42:47
@ Gabriel:這在標準的第27.7.3.6.3節中有描述。 – 2012-07-11 21:59:01