Sign in to follow this  

How to insert a number into a string using stringstream?

This topic is 4207 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

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].

Share this post


Link to post
Share on other sites
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.

Share this post


Link to post
Share on other sites
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.)

Share this post


Link to post
Share on other sites
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.

Share this post


Link to post
Share on other sites

This topic is 4207 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this