Saturday, August 31, 2019

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?



(1)



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



(2)



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

Answer



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  

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


is therefore the shortest way I can think of. You can even omit naming the type, using the auto keyword:



auto s = std::to_string(42);



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


No comments:

Post a Comment

hard drive - Leaving bad sectors in unformatted partition?

Laptop was acting really weird, and copy and seek times were really slow, so I decided to scan the hard drive surface. I have a couple hundr...