snippetcppMajor
How can I convert int to string in C++?
Viewed 0 times
howintconvertcanstring
Problem
How can I convert from
(1)
(2)
int to the equivalent string in C++? I am aware of two methods. Is there another 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();Solution
You can use
Or, if performance is critical (for example, if you do lots of conversions), you can use
Or a C string:
The latter doesn't do any dynamic memory allocations and is more than 70% faster than libstdc++ implementation of
Disclaimer: I'm the author of the {fmt} library.
std::to_string available in C++11 as suggested by Matthieu M.:std::string s = std::to_string(42);Or, if performance is critical (for example, if you do lots of conversions), you can use
fmt::format_int from the {fmt} library to convert an integer to std::string:std::string s = fmt::format_int(42).str();Or a C string:
fmt::format_int f(42);
const char* s = f.c_str();The latter doesn't do any dynamic memory allocations and is more than 70% faster than libstdc++ implementation of
std::to_string on Boost Karma benchmarks. See Converting a hundred million integers to strings per second for more details.Disclaimer: I'm the author of the {fmt} library.
Code Snippets
std::string s = std::to_string(42);std::string s = fmt::format_int(42).str();fmt::format_int f(42);
const char* s = f.c_str();Context
Stack Overflow Q#5590381, score: 68
Revisions (0)
No revisions yet.