What is the easiest way to convert from int
to equivalent string
in C++. I am aware of two methods. Is there any easier way?
(1)
int a = 10;
char *intStr = itoa(a);
string str = string(intStr);
(2)
int a = 10;
stringstream ss;
ss << a;
string str = ss.str();
Best Answer
C++11 introduces
std::stoi
(and variants for each numeric type) andstd::to_string
, the counterparts of the Catoi
anditoa
but expressed in term ofstd::string
.is therefore the shortest way I can think of. You can even omit naming the type, using the
auto
keyword:Note: see [string.conversions] (21.5 in n3242)