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();
If you need fast conversion of an integer with a fixed number of digits to char* left-padded with '0', this is a convenient example:
If you are converting a two-digit number:
If you are converting a three-digit number:
If you are converting a four-digit number:
And so on up to seven-digit numbers :)
sprintf is a well known one to insert any data into a string of required format .
You can convert char * array to string as shown in the third line.
I usually use the following method:
described in details here.
For C++98, there's a few options:
boost/lexical_cast
Boost is not a part of the C++ library, but contains many useful library extensions.
As for runtime, the
lexical_cast
operation takes about 80 microseconds (on my machine) on the first conversion, and then speeds up considerably afterwards if done redundantly.itoa
This means that
gcc
/g++
cannot compile code usingitoa
.No runtime to report. I don't have Visual Studio installed, which is reportedly able to compile
itoa
.sprintf
sprintf
is a C standard library function that works on C strings, and is a perfectly valid alternative.The
stdio.h
header may not be necessary. As for runtime, thesprintf
operation takes about 40 microseconds (on my machine) on the first conversion, and then speeds up considerably afterwards if done redundantly.stringstream
This is the C++ library's main way of converting integers to strings, and vice versa. There are similar sister functions to
stringstream
that further limit the intended use of the stream, such asostringstream
. Usingostringstream
specifically tells the reader of your code that you only intend to use the<<
operator, essentially. This function is all that's particularly necessary to convert an integer to a string. See this question for a more elaborate discussion.As for runtime, the
ostringstream
operation takes about 71 microseconds (on my machine), and then speeds up considerably afterwards if done redundantly, but not by as much as the previous functions.Of course there are other options, and you can even wrap one of these into your own function, but this offers an analytical look at some of the popular ones.