I have the following code, and I dont quite understand why the results happens to be like the one below:
#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;
}
Output:
Before1
Oh my god
After1
Before2
Where is the rest??¿ It only gets outputted when We uncomment the above lines... What happens internally? Does anybody know? =) Would be interesting...
Check whether the fail bit is set on cout
. You could also just clear the fail bit, with cout.clear()
.
Here's the rule from the Standard (section 27.7.3.6.3) that requires that the fail bit will be set in this case:
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 callssetstate(badbit)
(which may throwios_base::failure
).Gets characters from
sb
and inserts them in*this
. Characters are read fromsb
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 throwios_base::failure
). If an exception was thrown while extracting a character, the function setsfailbit
in error state, and iffailbit
is on inexceptions()
the caught exception is rethrown.Returns:
*this
.