views:

306

answers:

2

I've been working with somebody else's code and noticed that on all uses of ostringsteam they are in the habit of explicitly appending std::ends.

This is something I've never done and have never encountered a problem.

It doesn't appear to, but should std::ends make any difference in the following code?

ostringstream message;
message << "Hello world, version " << 2 /* << std::ends ??? */;
printf( "%s\n", message.str().c_str() );
+7  A: 

Appending std::ends is nonsense here since stringstream’s c_str returns a null-terminated char*. The same was not the case for the (now deprecated) strstreams where appending std::ends was necessary. I believe the author simply didn’t know of this changed behaviour.

Konrad Rudolph
+1 good answer. There are some scenarios for stringstream where `ends` can be useful though: http://stackoverflow.com/questions/624260/how-to-reuse-an-ostringstream/624291#624291
Johannes Schaub - litb
Notwithstanding the above link where ends is useful, they can be hazardous insofar as putting in an "extra" character where none was expected. My co-worker wondered why his stringstream constructed string was not identically equal to the one from the database, and it was because it had an embedded \0 character.
sdg
+2  A: 

It shouldn't, c_str() returns NUL-terminated string, anyway.

Michael Krelin - hacker