Nemo Nemo - 8 months ago 38
C++ Question

Easiest way to convert int to string in C++

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?


int a = 10;
char *intStr = itoa(a);
string str = string(intStr);


int a = 10;
stringstream ss;
ss << a;
string str = ss.str();


C++11 introduces std::stoi (and variants for each numeric type) and std::to_string, the counterparts of the C atoi and itoa but expressed in term of std::string.

#include <string> 

std::string s = std::to_string(42);

is therefore the shortest way I can think of.

Note: see [string.conversions] (21.5 in n3242)