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"
?
If you'd like to use
+
for concatenation of anything which has an output operator, you can provide a template version ofoperator+
:Then you can write your concatenations in a straightforward way:
Output:
This isn't the most efficient way, but you don't need the most efficient way unless you're doing a lot of concatenation inside a loop.
With the {fmt} library:
A subset of the library is proposed for standardization as P0645 Text Formatting and, if accepted, the above will become:
Disclaimer: I'm the author of the {fmt} library.
As a Qt-related question was closed in favour of this one, here's how to do it using Qt:
The string variable now has someIntVariable's value in place of %1 and someOtherIntVariable's value at the end.
Suggesting an alternate solution for people like me who may not have access to C++ 11 and additional libraries/headers like boost. A simple conversion works like this:
Example the number is 4, to convert 3 into ascii we can simply use the code:
char a='0'+4
This will immediately store 4 as a character in a.
From here, we can simply concatenate a with the rest of the string.
Shamelessly stolen from http://www.research.att.com/~bs/bs_faq2.html.
If you have C++11, you can use
std::to_string
.Example:
Output: