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

## 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 on other sites
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 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;}

1. 1
Rutin
67
2. 2
3. 3
4. 4
5. 5

• 21
• 10
• 33
• 20
• 9
• ### Forum Statistics

• Total Topics
633416
• Total Posts
3011780
• ### Who's Online (See full list)

There are no registered users currently online

×