Go back to Richel Bilderbeek's homepage.

Go back to Richel Bilderbeek's C++ page.

 

 

 

 

 

(C++) IntToStr

 

IntToStr is a code snippet to convert an int to std::string. To convert a std::string to int, use StrToInt.

 

IntToStr has multiple versions:

 

 

 

 

 

 

C++98STL IntToStr using the C++98 and the STL

 

#include <stdexcept>
#include <sstream>

//From http://www.richelbilderbeek.nl/CppIntToStr.htm
const std::string IntToStr(const int x)
{
  std::ostringstream s;
  if (!(s << x)) throw std::logic_error("IntToStr failed");
  return s.str();
}

 

The code snippet above was modified from the C++ FAQ Lite.

 

 

 

 

 

C++98Boost IntToStr using the C++98 and the Boost library

 

#include <string>
#include <boost/lexical_cast.hpp>

//From http://www.richelbilderbeek.nl/CppIntToStr.htm
const std::string IntToStr(const int x)
{
  return boost::lexical_cast<std::string>(x);
}

 

 

 

 

 

C++11STL IntToStr using the C++11 and the STL

 

#include <string>

//From http://www.richelbilderbeek.nl/CppIntToStr.htm
const std::string IntToStr(const int x)
{
  return std::to_string(x);
}

 

 

 

 

 

External links

 

 

 

 

 

 

Go back to Richel Bilderbeek's C++ page.

Go back to Richel Bilderbeek's homepage.

 

Valid XHTML 1.0 Strict