String to Int

How to Convert a String to an Int in C++

Learn how to convert a string to an int in C++ using std::stoi, handle bad or out-of-range input, and try std::from_chars, with clear code examples.

On this page
  1. The short answer
  2. How std::stoi reads the text
  3. Handling bad input
  4. Checking for leftover characters
  5. Other sizes and bases
  6. Using std::from_chars
  7. Using a string stream
  8. Common mistakes
  9. Converting several numbers from one line
  10. Choosing a method
  11. Summary

The short answer

The simplest way to convert a string to an int in modern C++ is std::stoi. It comes from the <string> header and was added in C++11. Pass it a std::string, and it returns an int:

#include <iostream>
#include <string>

int main() {
    std::string text = "42";
    int number = std::stoi(text);
    std::cout << number + 1 << '\n';  // prints 43
}

std::stoi behaves like the C function strtol, but it reports errors with exceptions. The rest of this guide covers how it reads text, how to handle bad input, and the other options.

How std::stoi reads the text

std::stoi reads the string from the beginning:

  • It skips leading whitespace, such as spaces and tabs.
  • It accepts an optional + or - sign.
  • It reads decimal digits and stops at the first character that isn’t a digit.

Anything after that point is ignored. So "42abc" converts to 42 without an error, and " -17" converts to -17. If you need to catch leftover text, see the position check below.

Handling bad input

Two kinds of input cause errors:

  • No digits at all, such as "hello". std::stoi throws a std::invalid_argument.
  • A number too big for an int, such as "99999999999" on a system where int is 32 bits. std::stoi throws a std::out_of_range.

Both exception types are defined in <stdexcept>. Wrap the call in a try block to handle them:

#include <iostream>
#include <stdexcept>
#include <string>

int main() {
    std::string text = "hello";
    try {
        int number = std::stoi(text);
        std::cout << number << '\n';
    } catch (const std::invalid_argument &) {
        std::cout << "That is not a number.\n";
    } catch (const std::out_of_range &) {
        std::cout << "That number is too large for an int.\n";
    }
}

If nothing catches the exception, the program stops. A try block is a good habit whenever the text comes from outside your program.

Checking for leftover characters

std::stoi takes an optional second argument, a pointer to a std::size_t. It is set to the position of the first character the function didn’t convert. If that position isn’t the end of the string, something was left over:

#include <iostream>
#include <string>

int main() {
    std::string text = "123abc";
    std::size_t used = 0;
    int number = std::stoi(text, &used);
    if (used != text.size()) {
        std::cout << "Found " << number << ", then extra characters.\n";
    }
}

Other sizes and bases

The same family of functions covers other integer types:

Function Returns
std::stoi int
std::stol long
std::stoll long long
std::stoul unsigned long
std::stoull unsigned long long

The unsigned versions accept a minus sign and convert it as an unsigned value. Check the input first if negative numbers are possible.

The third argument sets the base. For hexadecimal text, pass 16:

int value = std::stoi("ff", nullptr, 16);  // 255

Using std::from_chars

C++17 added std::from_chars in the <charconv> header. It doesn’t throw. Instead, it returns a result with an error code and a pointer to where parsing stopped. It’s stricter than std::stoi: it doesn’t skip leading whitespace and doesn’t accept a leading +, though it does accept -.

#include <charconv>
#include <iostream>
#include <string>
#include <system_error>

int main() {
    std::string text = "123";
    int number = 0;
    const char *first = text.data();
    const char *last = text.data() + text.size();

    auto [ptr, ec] = std::from_chars(first, last, number);
    if (ec == std::errc() && ptr == last) {
        std::cout << number << '\n';  // prints 123
    }
}

Check both the error code and the pointer. The pointer should match the end of the string when every character was used.

Using a string stream

If your program already uses streams, you can read an int from a std::istringstream:

#include <iostream>
#include <sstream>

int main() {
    std::istringstream in("42");
    int number = 0;
    if (in >> number) {
        std::cout << number << '\n';  // prints 42
    }
}

This works for clean input, but the stream doesn’t report leftover text on its own. "42abc" also reads as 42. For strict checks, use std::stoi with a position argument or std::from_chars. For more on how streams handle text, see c string stream.

Common mistakes

  • Using atoi in new C++ code. It returns 0 for bad input, the same value you get from "0", so the two cases can’t be told apart.
  • Forgetting to catch exceptions. If std::stoi throws and nothing catches the exception, the program ends.
  • Assuming any number fits in an int. Use std::stoll for larger values.
  • Expecting strict parsing. std::stoi skips leading spaces and ignores trailing text. Check the input if that matters to your program.

Converting several numbers from one line

If a line holds several numbers, such as "10,20,30", split it into pieces first and convert each piece. The steps for splitting are in c split string by delimiter. Then pass each piece to std::stoi.

Choosing a method

  • Use std::stoi, std::stol, or std::stoll for a simple call that throws on errors.
  • Use std::from_chars when you want an error code instead of exceptions, or strict parsing with no leading spaces.
  • Use a string stream when you’re already reading other values with >>.
  • Use atoi only when you’re maintaining C code that already uses it.

Summary

For most C++ code, std::stoi inside a try block is a solid default. Use std::from_chars when you want an error code instead. Where the text comes from matters too: for reading it from the user, see c input string. Going the other way, from an int to text, is covered in c convert int to string. A single character is a different case; see c char to int.

Keep exploring

Guides from other topics

All topics →

Class Constructors in C++

Learn C++ class constructors with compilable examples: default and parameterized forms, member initializer lists, explicit, and initialization order.

Constructors 6 min read

Friend Functions in C++

Learn what a friend function is in C++, how the friend keyword lets a non-member function reach private members, and when to use one, with code examples.