How to insert a number into a string using stringstream?

Started by
3 comments, last by eektor 17 years, 10 months ago
Since I couldn't find any information in my C++ books, I checked the web and wanted to make sure I understood it. I figured I needed to do this: std::ostringstream strout; strout << "Computer Score: " << g_comp_score << std::endl; Then if I were to put std::cout << strout.str(); It should print out "Computer Score: (whatever number g_comp_score is)", right? To clear strout, I would have to do: strout.str(""); Am I correct? Another thing is when I display the string (using SDL), a little box comes out after the number. If it was supposed to be 1, you would see 1[little box].
Advertisement
Yes, that's correct at first glance. The little box is likely the line-feed character (\r). Since you're on a windows box, std::endl will be \r\n, and SDL probably doesn't ignore the \r properly, and the font doesn't have a character for it (hence the box). Try leaving off the endl, or using explicitly a newline; see if the box goes away.
That works! Thanks.
Note that you don't need to do this if you're just going to output directly to cout (the whole reason the stringstream trick works is because the *stream interface* provides this functionality, and the console output stream certainly provides that interface too). Of course you will need it if you're constructing a string to pass to SDL :) (Remember that .str() yields a std::string; if you need to pass a const char* to some API function, you can chain a couple calls: .str().c_str(), and you're good to go.)
I just put the cout there so I could keep the example simple. I just wanted the string to pass it into my text renderer function which would then use the string and convert it into a c string for the SDL function call. Thanks for letting me know about the chaining, I did not know that.

This topic is closed to new replies.

Advertisement