Stringstream.rdbuf calls cout

I was surprised to see that my program suddenly calmed down when I added cout at some point, so I highlighted 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 a final shutdown. What's happening? If I changed the last .rdbuf() to .str() , then finished.

+5
source share
1 answer

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

std::cout<<data.str()<<std::endl; will not cause cout go into a failed state, because data.str() returns a copy of the base string regardless of where it was read (in any case, for strings in mixed mode).

+6
source

Source: https://habr.com/ru/post/1242506/


All Articles