Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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().

like image 739
JBL Avatar asked Mar 09 '13 05:03

JBL


2 Answers

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.

like image 167
user93353 Avatar answered Sep 27 '22 21:09

user93353


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.

like image 32
user1633759 Avatar answered Sep 27 '22 21:09

user1633759