Anonymous Entity
Anonymous Entity

Reputation: 3350

stringstream.rdbuf causing cout to fail

I was surprised to see my program suddenly go quiet when I added a cout at some point, so I isolated the responsible code:

std::stringstream data;
data<<"Hello World\n";
std:std::fstream file{"hello.txt", std::fstream::out};
file<<data.rdbuf();
std::cout<<"now rdbuf..."<<std::endl;
std::cout<<data.rdbuf()<<std::endl;
std::cout<<"rdbuf done."<< std::endl;

The program quietly exits without the final cout. What is going on? If I change the last .rdbuf() to .str() instead then it completes.

Upvotes: 5

Views: 552

Answers (1)

user657267
user657267

Reputation: 21000

During the call to std::cout<<data.rdbuf(), std::cout is unable to read any characters from data's filebuf because the read position is already at the end of the file after the previous output; accordingly, this sets failbit on std::cout, and until this state is cleared any further output will fail too (i.e. your final line is essentially ignored).

std::cout<<data.str()<<std::endl; will not cause cout to enter a failed state because data.str() returns a copy of the underlying string regardless of where the read position is (for mixed-mode stringstreams anyway).

Upvotes: 6

Related Questions