How to convert int to string in every C++ standard
What is the easiest way to convert from int
to string
in C++? In this post
we will take a quick look on how to do it in every standard (up to c++20).
Contents
c++98
A macro that uses std::ostringstream
is the easiest way in this standard,
just define it in a central header of your C++ sources:
#include <sstream>
#define SSTR( x ) static_cast< std::ostringstream & >( \
( std::ostringstream() << std::dec << x ) ).str()
Usage:
int foo = 42;
std::string foo_str = SSTR(i);
// or using streams to concatenate
std::string bar = SSTR("foo is: " << i << ", foo square is: " << i * i);
Another method, more clean (it's not a macro), but without support for
concatenating could be using ostringstream
in a template, like this:
template <typename T>
std::string to_string(T n) {
std::ostringstream ss;
ss << n;
return ss.str();
}
Usage:
int foo = 42;
std::string foo = to_string(i);
c++11
This standard introduces std::stoi
(and variants for each numeric type) and
std::to_string
, the counter parts of the C atoi()
and itoa()
, but maybe
you find the c++98 sstream macro more useful, up to you what method to use:
int foo = 42;
std::string foo_str = std::to_string(foo);
c++17
You can still use the c++11 std::to_string
, but in c++17 we have a way to do
the original macro based solution without going through macro ugliness
using a variadic template:
template < typename... Args >
std::string sstr( Args &&... args ) {
std::ostringstream sstr;
// fold expression
( sstr << std::dec << ... << args );
return sstr.str();
}
Usage:
int foo = 42;
std::string foo_str = sstr(i);
// or using streams to concatenate
std::string bar = sstr("foo is: ", i, " , foo square is: ", i * i);
c++20
std::format is the idiomatic way in c++20.
the <format>
library is very extensive and has many functionalities
so I cover it in another post: