Converting an int to std::string

What is the shortest way, preferably inline-able, to convert an int to a string? Answers using stl and boost will be welcomed.


Solution 1:

You can use std::to_string in C++11

int i = 3;
std::string str = std::to_string(i);

Solution 2:

#include <sstream>
#include <string>
const int i = 3;
std::ostringstream s;
s << i;
const std::string i_as_string(s.str());

Solution 3:

boost::lexical_cast<std::string>(yourint) from boost/lexical_cast.hpp

Work's for everything with std::ostream support, but is not as fast as, for example, itoa

It even appears to be faster than stringstream or scanf:

  • http://www.boost.org/doc/libs/1_53_0/doc/html/boost_lexical_cast/performance.html

Solution 4:

Well, the well known way (before C++11) to do that is using the stream operator :

#include <sstream>

std::ostringstream s;
int i;

s << i;

std::string converted(s.str());

Of course, you can generalize it for any type using a template function ^^

#include <sstream>

template<typename T>
std::string toString(const T& value)
{
    std::ostringstream oss;
    oss << value;
    return oss.str();
}

Solution 5:

If you cannot use std::to_string from C++11, you can write it as it is defined on cppreference.com:

std::string to_string( int value ) Converts a signed decimal integer to a string with the same content as what std::sprintf(buf, "%d", value) would produce for sufficiently large buf.

Implementation

#include <cstdio>
#include <string>
#include <cassert>

std::string to_string( int x ) {
  int length = snprintf( NULL, 0, "%d", x );
  assert( length >= 0 );
  char* buf = new char[length + 1];
  snprintf( buf, length + 1, "%d", x );
  std::string str( buf );
  delete[] buf;
  return str;
}

You can do more with it. Just use "%g" to convert float or double to string, use "%x" to convert int to hex representation, and so on.