Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

difference between << s.str() and << s.rdbuf()

Can someone explain the subtle difference in:

ofstream f("test.txt")
std::stringstream s;
s<<"";
f << s.rdbuf();
f.good() // filestream is bad!!


ofstream f("test.txt")
std::stringstream s;
s<<"";
f << s.str();
f.good() // is still ok!

I mostly use .rdbuf() to push the stringstream to the file (because its more efficient), but if the stringstream is empty than the filestream gets bad...? Isnt this stupid? I think I dont quite understand << s.rdbuf() ...

like image 494
Gabriel Avatar asked Oct 29 '14 23:10

Gabriel


People also ask

What is the difference between Stringstream and Istringstream?

A stringstream is an iostream object that uses a std::string as a backing store. An ostringstream writes to a std::string . An istringstream reads from a std::string . You read & write from & to an istringstream or ostringstream using << and >> , just like any other iostream object.

What does Rdbuf stand for?

Raw Device/Data Buffer (rdbuf) <---- I prefer @Daniel Jour's comments.


1 Answers

The insertion operator that "inserts" streambuffers sets the failbit if no characters could be extracted from the streambuffer - [ostream.inserters]/9:

If the function inserts no characters, it calls setstate(failbit) (which may throw ios_base:: failure (27.5.5.4)).

Whereas the insertion operator that outputs a string obviously doesn't consider the amount of characters written.

It seems that this is because inserting a streambuffer "forwards" the streambuffer into the stream - if no characters could be extracted most certainly there was an error in the streambuffer itself and this error should be represented by the streams error state. Outputting an empty stream is an exception that was presumably not considered important enough to take into account when this rule was created.

like image 59
Columbo Avatar answered Sep 30 '22 16:09

Columbo