c++ - cout stringstream 两次以损坏的 cout 结束(最小示例)

标签 c++ cout stringstream streambuf

我有下面的代码,我不太明白为什么结果恰好像下面这样:

#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

其余的在哪里??¿只有当我们取消注释上面的行时才会输出... 内部发生了什么?有人知道吗? =) 会很有趣...

最佳答案

检查cout上是否设置了失败位.您也可以使用 cout.clear() 清除失败位.


这是标准(第 27.7.3.6.3 节)中的规则,要求在这种情况下设置失败位:

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

Effects: Behaves as an unformatted output function. After the sentry object is constructed, if sb is null calls setstate(badbit) (which may throw ios_base::failure).

Gets characters from sb and inserts them in *this. Characters are read from sb and inserted until any of the following occurs:

  • end-of-file occurs on the input sequence;
  • inserting in the output sequence fails (in which case the character to be inserted is not extracted);
  • an exception occurs while getting a character from sb.

If the function inserts no characters, it calls setstate(failbit) (which may throw ios_base::failure). If an exception was thrown while extracting a character, the function sets failbit in error state, and if failbit is on in exceptions() the caught exception is rethrown.

Returns: *this.

关于c++ - cout stringstream 两次以损坏的 cout 结束(最小示例),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11441665/

相关文章:

c++ - 计算数组的大小

c++ - 什么时候应该在 C++ 中使用 "this"关键字?

c++ - 有什么办法可以用 base64 计算出来吗?

c++ - 如何使用cout以全精度打印 double 值?

c++ - 是否可以在 C++ 中处理字符串流中的单个元素

c++ - istream 的 operator>> (double& val) 在 libc++ 和 libstdc++ 之间的差异

c++ - 使用 OpenCV 中的图像处理技术对商店进行人数统计

c++ - auto 和 decltype(auto) 类型推导示例

c++ - 如何用cout设置固定宽度?

c++ - 相当于 %02d 与 std::stringstream?