c++ - stringstream.rdbuf causing cout to fail -
i surprised see program go quiet when added cout @ point, isolated 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 final cout. going on? if change last .rdbuf()
.str()
instead completes.
during call std::cout<<data.rdbuf()
, std::cout
unable read characters data
's filebuf
because read position @ end of file after previous output; accordingly, sets failbit
on std::cout
, , until state cleared further output fail (i.e. final line ignored).
std::cout<<data.str()<<std::endl;
not cause cout
enter failed state because data.str()
returns copy of underlying string regardless of read position (for mixed-mode stringstreams anyway).
Comments
Post a Comment