C++ string objects, how do I add an integer?
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.
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"
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;}
This topic is closed to new replies.
Advertisement
Popular Topics
Advertisement