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"
?
In C++11, you can use
std::to_string
, e.g.:If you have Boost, you can convert the integer to a string using
boost::lexical_cast<std::string>(age)
.Another way is to use stringstreams:
A third approach would be to use
sprintf
orsnprintf
from the C library.Other posters suggested using
itoa
. This is NOT a standard function, so your code will not be portable if you use it. There are compilers that don't support it.There is a function I wrote, which takes the int number as the parameter, and convert it to a string literal. This function is dependent on another function that converts a single digit to its char equivalent:
Herb Sutter has a good article on this subject: "The String Formatters of Manor Farm". He covers
Boost::lexical_cast
,std::stringstream
,std::strstream
(which is deprecated), andsprintf
vs.snprintf
.Without C++11, for a small integer range, I found this is all I needed:
Declare/include some variant of the following somewhere:
Then:
It works with enums too.
In alphabetical order:
#include <string>
)#include <sstream>
(from standard C++)