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)
For C++98, there's a few options:
boost/lexical_castBoost is not a part of the C++ library, but contains many useful library extensions.
The
lexical_castfunction template offers a convenient and consistent form for supporting common conversions to and from arbitrary types when they are represented as text.
-- Boost's Documentation
#include "boost/lexical_cast.hpp"
#include
int main() {
int x = 5;
std::string x_str = boost::lexical_cast(x);
return 0;
}
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.
itoaThis function is not defined in ANSI-C and is not part of C++, but is supported by some compilers.
-- cplusplus.com
This means that gcc/g++ cannot compile code using itoa.
#include
int main() {
int x = 5;
char * x_str = new char[2];
x_str = itoa(x, x_str, 10); // base 10
return 0;
}
No runtime to report. I don't have Visual Studio installed, which is reportedly able to compile itoa.
sprintfsprintf is a C standard library function that works on C strings, and is a perfectly valid alternative.
Composes a string with the same text that would be printed if format was used on printf, but instead of being printed, the content is stored as a C string in the buffer pointed by str.
-- cplusplus.com
#include
int main() {
int x = 5;
char * x_str = new char[2];
int chars_written = sprintf(x_str, "%d", x);
return 0;
}
The stdio.h header may not be necessary. As for runtime, the sprintf operation takes about 40 microseconds (on my machine) on the first conversion, and then speeds up considerably afterwards if done redundantly.
stringstreamThis 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 as ostringstream. Using ostringstream 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.
#include
#include
int main() {
int x = 5;
std::ostringstream stream;
stream << x;
std::string x_str = stream.str();
return 0;
}
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.