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?
One method here is directly printing the output if its required in your problem.
Else, one of the safest method is to use
And then copy it to your "text" string .
Thus, you have your required output string
For more info on
sprintf
, follow: http://www.cplusplus.com/reference/cstdio/sprintfThese work for general strings (in case you do not want to output to file/console, but store for later use or something).
boost.lexical_cast
String streams
With C++11, you can write:
You also try concatenate player's number with
std::string::push_back
:Example with your code:
You will see in console: