What's the difference between istringstream, ostringstream and stringstream? / Why not use stringstream in every case?

Oliver Baur picture Oliver Baur · Jul 20, 2010 · Viewed 69.9k times · Source

When would I use std::istringstream, std::ostringstream and std::stringstream and why shouldn't I just use std::stringstream in every scenario (are there any runtime performance issues?).

Lastly, is there anything bad about this (instead of using a stream at all):

std::string stHehe("Hello ");

stHehe += "stackoverflow.com";
stHehe += "!";

Answer

CB Bailey picture CB Bailey · Jul 20, 2010

Personally, I find it very rare that I want to perform streaming into and out of the same string stream.

Usually I want to either initialize a stream from a string and then parse it; or stream things to a string stream and then extract the result and store it.

If you're streaming to and from the same stream, you have to be very careful with the stream state and stream positions.

Using 'just' istringstream or ostringstream better expresses your intent and gives you some checking against silly mistakes such as accidental use of << vs >>.

There might be some performance improvement but I wouldn't be looking at that first.

There's nothing wrong with what you've written. If you find it doesn't perform well enough, then you could profile other approaches, otherwise stick with what's clearest. Personally, I'd just go for:

std::string stHehe( "Hello stackoverflow.com!" );