1

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...

Ben Voigt
  • 277,958
  • 43
  • 419
  • 720
Gabriel
  • 8,990
  • 6
  • 57
  • 101

1 Answers1

4

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 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.

Community
  • 1
  • 1
Ben Voigt
  • 277,958
  • 43
  • 419
  • 720
  • This is likely it, the libstdc++ documentation has this to say about the `__ostream_type& operator<<(__streambuf_type* __sb);` "If the function inserts no characters, failbit is set." Which seems plausible, since the `s.rdbuf()` would be positioned at its end the 2. time one tries to print it. – nos Jul 11 '12 at 21:42
  • Oh, thanks ! That was the point! Where can we read in the libstdc++ docu? – Gabriel Jul 11 '12 at 21:42
  • 1
    @Gabriel: This is described in section 27.7.3.6.3 in the Standard. – Ben Voigt Jul 11 '12 at 21:59