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() );
markh44
  • 5,804
  • 5
  • 28
  • 33

2 Answers2

11

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
  • 530,221
  • 131
  • 937
  • 1,214
  • +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 Sep 02 '09 at 12:29
  • 2
    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 Sep 02 '09 at 12:57
3

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

Michael Krelin - hacker
  • 138,757
  • 24
  • 193
  • 173