2012-07-11 36 views
1

我有下面的代碼兩次結束了,我不明白爲什麼結果恰好是像下面這樣: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 

其餘的地方??只有當我們取消註釋上述行時才輸出... 內部會發生什麼?有人知道嗎? =)會很有趣......

回答

4

檢查是否在cout上設置了失敗位。您也可以僅清除失敗位,cout.clear()


下面是來自標準(部分27.7.3.6.3),要求該故障位會在這種情況下設置的規則:

basic_ostream<charT,traits>& operator<<(basic_streambuf<charT,traits>* sb);

影響:表現爲一個無格式輸出功能。在構建哨兵對象之後,如果sb爲空,則調用setstate(badbit)(這可能會拋出ios_base::failure)。

sb獲取字符並將它們插入*this。字符從sb讀取和插入,直到發生以下的:

  • 檔案結尾發生在輸入序列;
  • 在輸出序列中插入失敗(在這種情況下,未插入要插入的字符);
  • sb獲取字符時發生異常。

如果函數插入任何字符,它調用setstate(failbit)(其可能拋出ios_base::failure)。如果在提取字符拋出了一個異常,該功能處於錯誤狀態設置failbit,如果failbit是在exceptions()捕捉到的異常被重拋出。

返回:*this

+0

這可能是它的的libstdC++文檔已經這樣說了'__ostream_type& 運營商<<(__ streambuf_type * __sb);' 「如果函數沒有插入字符,failbit設置。」這看起來似乎是合理的,因爲's.rdbuf()'會在第二次嘗試打印時結束。 – nos 2012-07-11 21:42:09

+0

哦,謝謝!這就是要點!我們可以在libstdC++ docu中讀取哪些內容? – Gabriel 2012-07-11 21:42:47

+1

@ Gabriel:這在標準的第27.7.3.6.3節中有描述。 – 2012-07-11 21:59:01