How to convert string to int and int to string in C++

It is common to convert string to int and int to string in C++ programs. This post introduces how to convert a valid string to int and int to string in C++ using C and C++ ways and libraries. If your string is not a valid integer string, you should check it first or use other methods.

cpp photo

Convert string to int

1. The C-style way

Use C standard library strtol (avoid atoi() which does not report errors).

#include <stdlib.h>

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

Example C++ code:

#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;
}

2. The C++-style way

Way 1. You can use the C standard library as above in C++ too.

Way 2. Use C++ standard library std::stringstream.

#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;
}

Way 3. Use std::stoi() from C++ standard library since C++11.

#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;
}

Convert int to string

1. The C-style way

Use C standard library function snprintf().

#include <stdio.h>

int snprintf(char *str, size_t size, const char *format, ...);

The functions snprintf() and vsnprintf() write at most size bytes (including the terminating null byte ('\0')) to str.
#include <cstdio>

#define MAX_BUFFER_SIZE 128

int main()
{
  int number = 123;
  char out_string [MAX_BUFFER_SIZE];
  snprintf(out_string, MAX_BUFFER_SIZE, "%d", number);
  printf("out_string = \"%s\"\n", out_string);
  return 0;
}

2. The C++-style way

Way 1. You can use the C standard library as above in C++ too.

Way 2. Use C++ standard library std::stringstream.

#include <sstream>
#include <iostream>

int main()
{
  int i = 123;
  std::stringstream ss;
  ss << i;
  std::string out_string = ss.str();
  std::cout << out_string << "\n";
  return 0;
}

Way 3. Use C++ standard library std::to_string() available in standard library since C++11.

#include <iostream>
#include <string>

int main ()
{
  int n = 123;
  std::string str = std::to_string(n);
  std::cout << n << " ==> " << str << std::endl;

  return 0;
}

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 *