gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 02:03:46 31 4
gpt4 key购买 nike

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

#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/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com