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?
Another possibility is Boost.Format:
Your example seems to indicate that you would like to display the a string followed by an integer, in which case:
would work fine.
But, if you're going to be storing the string places or passing it around, and doing this frequently, you may benefit from overloading the addition operator. I demonstrate this below:
In fact, you can use templates to make this approach more powerful:
Now, as long as object
b
has a defined stream output, you can append it to your string (or, at least, a copy thereof).(Downvote my answer all you like; I still hate the C++ I/O operators.)
:-P
There are a few options, and which one you want depends on the context.
The simplest way is
or if you want this on a single line
If you are writing a single threaded program and if you aren't calling this code a lot (where "a lot" is thousands of times per second) then you are done.
If you are writing a multi threaded program and more than one thread is writing to cout, then this simple code can get you into trouble. Let's assume that the library that came with your compiler made cout thread safe enough than any single call to it won't be interrupted. Now let's say that one thread is using this code to write "Player 1" and another is writing "Player 2". If you are lucky you will get the following:
If you are unlucky you might get something like the following
The problem is that std::cout << text << i << endl; turns into 3 function calls. The code is equivalent to the following:
If instead you used the C-style printf, and again your compiler provided a runtime library with reasonable thread safety (each function call is atomic) then the following code would work better:
Being able to do something in a single function call lets the io library provide synchronization under the covers, and now your whole line of text will be atomically written.
For simple programs, std::cout is great. Throw in multithreading or other complications and the less stylish printf starts to look more attractive.
For the record, you can also use a
std::stringstream
if you want to create the string before it's actually output.