JBL
JBL

Reputation: 12907

Why does stringstream yields strange values?

So, I'm trying to use a stringstream in my program, in order to get some formatted string (esp. because I need to convert numbers to string).

The thing is, my program crashes, and when I debug it with Visual Studio, in my Spy window, I see that my stringstream's string buffer yields (when trying to add "Framerate" to it):

"FramerateÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍÍýýýý««««««««îþîþ"

Code :

std::stringstream s;
s << "Framerate";

My code then will crash the moment I try to get the associated string... I can't find any explanation for this, nor a problem with my code...

EDIT: Turns out these characters aren't the issue, and that the stringstream returns the expected string with str().

Upvotes: 7

Views: 4323

Answers (2)

user1633759
user1633759

Reputation: 56

In visual studio 2015 version 14.0.25431.01 Update 3 it looks like std::strstream does not ensure that the data returned by 'str()' is null terminated.

I ran a test with:

`std::strstream s;
 s << "the cow jumped over the moon!";
 return s.str();`

and got: the cow jumped over the moon!===zzzz

adding s.write("", 1); before the return fixed my output but is very unpleasant.

Upvotes: 1

user93353
user93353

Reputation: 14049

stringstream's internal buffer need not be null terminated. However, when you call str() on the stringstream object, you will get a null terminated string. It's highly likely the cause of your crash is elsewhere.

Upvotes: 7

Related Questions