Jump to content
  • Advertisement
Sign in to follow this  
darenking

C++ string objects, how do I add an integer?

This topic is 4888 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

I can add string objects together like this: myString = text1 + text2 + text3; where text1 etc are all string objects, but how do I add on an integer? I have tried like this: myString = text1 + value; where value is an integer but it doesn't compile. Presumably the integer has to be converted to a string in some way? If text1 is 'hello' and value is equal to 50, I want to end up with myString holding the text 'hello50'. Any ideas, clever people? Or do I have to use std::ostringstream? If so, I know how to do that, just wondering if there's a simpler way.

Share this post


Link to post
Share on other sites
Advertisement
You can use an std::stringstream object to do this. Basically, it acts like all other C++ I/O streams, but you can access its internal buffer as an std::string (you can set it and get it). Using a stringstream, you just need to use the input (<<) operator to concatenate something to the content. You just need to include the sstream header.



std::stringstream StringStream;

StringStream << "Hello" << "50";

std::string String = StringStream.str();

// String is now equal to "Hello50"


Share this post


Link to post
Share on other sites
Use a lexical cast. Boost has one, here's a simplified version:


template<typename R, typename T>
R lexical_cast(T const& t) {
R result;
std::stringstream ss;
if(!(ss<<t) || !(ss>>result)) {
throw std::bad_cast();
}
return result;
}

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!