Sign in to follow this  
darenking

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

Recommended Posts

darenking    122
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
Max_Payne    757
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
Washu    7829
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

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