This question already has an answer here:
- How to concatenate a std::string and an int? 29 answers
int i = 4;
string text = "Player ";
cout << (text + i);
I'd like it to print Player 4
.
The above is obviously wrong but it shows what I'm trying to do here. Is there an easy way to do this or do I have to start adding new includes?
Well, if you use cout you can just write the integer directly to it, as in
The C++ way of converting all kinds of objects to strings is through string streams. If you don't have one handy, just create one.
Alternatively, you can just convert the integer and append it to the string.
Finally, the Boost libraries provide
boost::lexical_cast
, which wraps around the stringstream conversion with a syntax like the built-in type casts.This also works the other way around, i.e. to parse strings.