IntToStr is a code snippet to convert an int to std::string. To convert a std::string to int, use StrToInt.
Operating system(s) or programming environment(s)
- Lubuntu 15.04 (vivid)
- Qt Creator 3.1.1
- G++ 4.9.2
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
#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"); }