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

It is common to convert string to int and int to string in C and C++ programs. This post introduces how to convert a valid string to int and int to string in C and C++. 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 way

Use C standard library

#include <cstdlib>
#include <string>

std::string text = "123";
int number = std::atoi (text.c_str());
if (errno == ERANGE) {
  // or may be std::errno
  // the number is too big/small
  // number = LONG_MAX or LONG_MIN
} else if (errno == ????) {
  //maybe EINVAL, E2BIG or EDOM (or ERANGE again)
  //unable to convert to a number
}

2. The C++ 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 <string>

std::string text = "123";
int number;
std::istringstream iss (text);
iss >> number;
if (!iss.good ()) {
  //something happened
}

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

#include <iostream>
#include <string>

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

  int n = std::stoi(str);

  std::cout << str << " --> " << n << std::endl;

  return 0;
}

Convert int to string

1. The C way

Use C standard library

#include <stdio.h>

const char base_string[] = "base_string";
char out_string [MAX_BUFFER_SIZE];
int number = 123;
sprintf(out_string, "%s%d", base_string, number);
printf("out_string = "%s"n", out_string);

2. The C++ 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>

int i = 123;
std::string out_string;
std::stringstream ss;
ss << i;
out_string = ss.str();

Way 3. Use C++ standard library std::to_string() 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 Z Ma

Eric is a father and 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.

Leave a Reply

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