4 Ways of Converting String to Int in C++

Posted on In Programming

It is common to convert a string (std::string) to integer (int) in C++ programs. Because of the long history of C++ which has several versions with extended libraries and supports almost all C standard library functions, there are many ways to convert a string to int in C++. This post introduces how to convert a string to an integer in C++ using C and C++ ways and libraries. If you would like to convert int to string, please check How to Convert Int to String in C++.

We can use the functions and classes provided by the C standard library and C++ standard library to convert string to int in C++.

String to int in C++: the “modern” C++-style way using std::stoi()

We can use the std::stoi() function from C++ standard library since C++11. The std::stoi() function is recommended to use if the development environment is not locked to the pre-C++11 standard.

Defined in header <string>
int stoi( const std::string& str, std::size_t* pos = 0, int base = 10 ); (1) (since C++11)

Discards any whitespace characters (as identified by calling isspace()) until the first non-whitespace character is found, then takes as many characters as possible to form a valid base-n (where n=base) integer number representation and converts them to an integer value.

std::out_of_range if the converted value would fall out of the range of the result type or if the underlying function (std::strtol or std::strtoll) sets errno to ERANGE.

One example C++ program to convert string to int using std::stoi() is as follows.

#include <iostream>
#include <string>

int main ()
{
  std::string str("123");

  try {
    int n = std::stoi(str);
    std::cout << n << "\n";
  }
  catch (...) {
    std::cerr << "ERROR!\n";
  }
  return 0;
}

If the parsing fails, std::stoi() will raise exceptions.

String to int in C++: the stream based C++-style way using string stream

Use C++ standard library’s string stream std::istringstream which can parse the string as an input stream for various types. In this way, we convert the string to int. The sstream header contains the function/class declaration for the string stream library.

#include <iostream>
#include <string>
#include <sstream>

int main()
{
  std::string text = "123";
  std::istringstream iss (text);
  int number;
  iss >> number;
  if (iss.fail()) {
    // something wrong happened
    std::cerr << "ERROR!\n";
    return 1;
  }
  std::cout << number << "\n";
  return 0;
}

We should check std::istringstream::fail() function to check whether there is any error during parsing the string.

String to int in C++: the Boost way using Spirit.X3 parser

Boost has a header only library Spirit.X3 that implements a parser for C++. It is a powerful parser that can easily parse integers with its numeric parsers. For parsing integer, we can use the boost::spirit::x3::int_ parser.

One usage example is as follows.


#include <iostream>

#include <boost/spirit/home/x3.hpp>

int main(int argc, char* args[])
{
   namespace x3 = boost::spirit::x3;
   using x3::int_;

   std::string str("123");

   // parse with boost spirit x3 int_ parser
   int value = 0;
   std::string::iterator strbegin = str.begin();
   x3::parse(strbegin, str.end(), int_, value);

   std::cout << value << "\n";

   return 0;
}

String to int in C++: the C-style way using strtol()

We can also use the C standard library function strtol (avoid atoi() which does not report errors) to convert string to int in C++.

#include <stdlib.h>

long int strtol(const char *nptr, char **endptr, int base);

An example C++ code using the strtol() function is as follows.

#include <iostream>
#include <cstdlib>
#include <string>

int main()
{
  std::string text{"123"};
  errno = 0; // pre set to 0
  int number = (int)std::strtol(text.c_str(), nullptr, 10);
  if (errno == ERANGE) {
    // the number is too big/small
    // number = (int)LONG_MAX or (int)LONG_MIN
    std::cerr << "Too big or small: " << errno << "\n";
    return 1;
  } else if (errno) {
    // maybe EINVAL, E2BIG or EDOM
    // unable to convert to a number
    std::cerr << "ERROR: " << errno << "\n";
    return 1;
  }
  // TODO: you need to check whether the long to int overflow too if neccessary
  std::cout << number << "\n";
  return 0;
}

The errors are reported in the C-style way by setting the errno. We should check the errno for any errors.

Eric Ma

Eric is a systems guy. Eric is interested in building high-performance and scalable distributed systems and related technologies. The views or opinions expressed here are solely Eric's own and do not necessarily represent those of any third parties.

4 comments

  1. Nice write up.
    You probably want to use iss.fail() instead, since !iss.good() would also trip on ‘end of stream’

Leave a Reply

Your email address will not be published. Required fields are marked *