Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

stringstream.rdbuf causing cout to fail

Tags:

c++

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.

like image 526
Anonymous Entity Avatar asked Feb 08 '16 01:02

Anonymous Entity


1 Answers

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

like image 129
user657267 Avatar answered Sep 17 '22 22:09

user657267