Jump to content
  • Advertisement
Sign in to follow this  
eektor

How to insert a number into a string using stringstream?

This topic is 4422 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
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.

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
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!