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.

Technical facts

 

Operating system(s) or programming environment(s)

IDE(s):

Project type:

C++ standard:

Compiler(s):

Libraries used:

 

 

 

 

 

Qt project file: ./CppIntToStr/CppIntToStr.pro

 

#-------------------------------------------------
#
# Project created by QtCreator 2011-08-05T19:31:46
#
#-------------------------------------------------
QT       += core
QT       -= gui
QMAKE_CXXFLAGS += -std=c++0x
TARGET = CppIntToStr
CONFIG   += console
CONFIG   -= app_bundle
TEMPLATE = app
SOURCES += main.cpp

 

 

 

 

 

./CppIntToStr/main.cpp

 

#include <string>

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

#include <sstream>
#include <stdexcept>
#include <string>

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

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

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

#include <cassert>

int main()
{
  assert(IntToStrCpp0x(123) == "123");
  assert(IntToStrBoost(123) == "123");
  assert(IntToStrCpp98(123) == "123");

  assert(IntToStrCpp0x(-123) == "-123");
  assert(IntToStrBoost(-123) == "-123");
  assert(IntToStrCpp98(-123) == "-123");

  assert(IntToStrCpp0x(0) == "0");
  assert(IntToStrBoost(0) == "0");
  assert(IntToStrCpp98(0) == "0");
}

 

 

 

 

 

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

Go back to Richel Bilderbeek's homepage.

 

Valid XHTML 1.0 Strict

This page has been created by the tool CodeToHtml