How to convert an int to a std::string in C++

Methods

  1. Use std::stringstream
  2. Use boost::lexical_cast
  3. Use folly::to()
  4. Use std::to_string (C++11)

Method 1: Use std::stringstream

#include <sstream>

template <typename T>
std::string to_string(const T& thing)
{
    std::stringstream ss;
    ss << thing;
    return ss.str();
}

template <>
std::string to_string<std::string>(const std::string& s)
{
    return s;
}

std::cout << ::to_string(n) << "\n";

Method 2: Use boost::lexical_cast

#include <boost/lexical_cast.hpp>
std::cout << boost::lexical_cast<std::string>(n) << "\n";

Reference: Boost.Lexical_Cast

Method 3: Use folly::to()

#include <folly/Conv.h>
std::cout << folly::to<std::string>(n) << "\n";

Reference: folly/Conv.h

Method 4: Use std::to_string (C++11)

std::cout << std::to_string(n) << "\n";

Related