I thought this would be really simple but it's presenting some difficulties. If I have
std::string name = "John";
int age = 21;
How do I combine them to get a single string "John21"
?
I thought this would be really simple but it's presenting some difficulties. If I have
std::string name = "John";
int age = 21;
How do I combine them to get a single string "John21"
?
This problem can be done in many ways. I will show it in two ways:
Convert the number to string using to_string(i).
Using string streams.
Code:
// Hope it helps
Here is an implementation of how to append an int to a string using the parsing and formatting facets from the IOStreams library.
Another easy way of doing it is:
I am a beginner C++ user and found this the easiest way:
This will successfully concatenate name and age, the the output will be "John21."
However there has to be a reason nobody said this; I think there may be a flaw in it although I haven't experienced any so far.
EDIT: I have realized that this is not necessarily the right answer, however I will keep it here in case any C++ beginners would like to know how to output concatenated strings.
The std::ostringstream is a good method, but sometimes this additional trick might get handy transforming the formatting to a one-liner:
Now you can format strings like this: