C++ example

How to convert a string to an int in C++

8 min read Updated Nov 2026 Runs in an isolated runtime
Quick answer

Use std::stoi from <string>: int n = std::stoi(text);. It throws std::invalid_argument when there are no digits and std::out_of_range when the number doesn't fit, but it quietly stops at the first non-digit, so "42abc" gives 42. For strict parsing without exceptions, use std::from_chars. A single digit char converts with c - '0'.

C++ has five standard ways to turn text into an int, and they disagree on the part that matters: what happens with bad input. std::stoi throws, std::from_chars returns an error code, a stream sets a fail flag, strtol sets errno, and atoi returns 0 and tells you nothing. The sections below cover each one, how to reject input like "42abc" that most of them accept, other bases, and converting a single char, then a table to pick from. Each example runs on this page: hit Run, then edit the code and run it again.

1std::stoiRecommended

std::stoi (C++11) takes a std::string and returns an int. It skips leading whitespace, accepts a + or - sign, and reports failure with an exception, so a bad value can't slip through as a number. Wrap the call in try whenever the text comes from a user, a file or the network. For wider types there are std::stol, std::stoll, std::stoul and std::stoull, which work the same way.

stoi_basic.cpp
#include <iostream>
#include <stdexcept>
#include <string>

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

    // Leading whitespace and a sign are accepted
    std::cout << std::stoi("  -17") << '\n';
    std::cout << std::stoi("+8") << '\n';

    // Bigger types have their own functions
    long long big = std::stoll("9000000000");
    unsigned long u = std::stoul("4000000000");
    std::cout << big << ' ' << u << '\n';

    // Bad input throws instead of returning a value
    for (std::string bad : {"abc", "", "99999999999"}) {
        try {
            std::cout << std::stoi(bad) << '\n';
        } catch (const std::invalid_argument& e) {
            std::cout << "invalid_argument (" << e.what() << ") for \"" << bad << "\"\n";
        } catch (const std::out_of_range& e) {
            std::cout << "out_of_range (" << e.what() << ") for \"" << bad << "\"\n";
        }
    }
}

Output

"42" becomes an int you can do arithmetic with (43), " -17" gives -17 and "+8" gives 8. Text with no digits and the empty string both throw std::invalid_argument, and "99999999999" throws std::out_of_range because it is bigger than an int holds. With GCC, e.what() is just the function name, stoi, so print the input yourself in error messages. An uncaught one ends the program with terminate called after throwing, which is why every call on outside input belongs in a try.

2Rejecting trailing characters, and other bases

The gotcha people find in production: std::stoi only throws when there are no digits at all. It reads as many as it can and ignores the rest, so "42abc", "3.99" and "12 34" all "succeed". Its second argument, a std::size_t*, receives the number of characters it used; compare that with the length to accept only a whole number. The third argument is the base, from 2 to 36, or 0 to let a 0x or 0 prefix decide.

stoi_pos.cpp
#include <cstddef>
#include <iostream>
#include <stdexcept>
#include <string>

// stoi that accepts only a whole number: no junk after the digits
int to_int_strict(const std::string& s, int base = 10) {
    std::size_t used = 0;
    int value = std::stoi(s, &used, base);  // throws on no digits / overflow
    if (used != s.size()) {
        throw std::invalid_argument("trailing characters: " + s.substr(used));
    }
    return value;
}

int main() {
    // Gotcha: stoi stops at the first character it can't use
    std::cout << std::stoi("42abc") << '\n';
    std::cout << std::stoi("3.99") << '\n';
    std::cout << std::stoi("12 34") << '\n';

    // The second argument tells you how many characters it used
    std::size_t used = 0;
    std::stoi("42abc", &used);
    std::cout << "used " << used << " of 5 chars\n";

    for (std::string s : {"123", "42abc", "3.99", "-8"}) {
        try {
            int n = to_int_strict(s);
            std::cout << s << " -> " << n << '\n';
        } catch (const std::invalid_argument& e) {
            std::cout << s << " -> rejected, " << e.what() << '\n';
        }
    }

    // The third argument is the base; 0 reads a 0x or 0 prefix
    std::cout << std::stoi("ff", nullptr, 16) << ' '
              << std::stoi("1010", nullptr, 2) << ' '
              << std::stoi("0x1A", nullptr, 0) << ' '
              << std::stoi("017", nullptr, 0) << '\n';
}

Output

The first three lines print 42, 3 and 12: no exception, the junk is dropped, and a decimal is truncated rather than rounded. The used count is 2 for "42abc", and to_int_strict turns that into 42abc -> rejected, trailing characters: abc while 123 and -8 pass. The bases line reads 255 10 26 15: hex ff, binary 1010, and with base 0, 0x1A as hex and 017 as octal. That is why base 0 does not belong on user input where a leading zero means nothing: "017" is 15, not 17.

3std::from_chars: strict, no exceptions (C++17)

std::from_chars from <charconv> is the low-level parser the standard added in C++17. It takes a pair of char pointers, so it works on a std::string, a std::string_view or a slice of a buffer without copying, and it returns a ptr (where parsing stopped) and an ec error code instead of throwing. It ignores the locale and allocates nothing, which makes it the fastest option and a good fit for code built without exceptions. Check both fields: ec for no digits or overflow, and ptr against the end for trailing junk.

from_chars.cpp
#include <charconv>
#include <iostream>
#include <optional>
#include <string>
#include <string_view>
#include <system_error>

// No exceptions, no allocation, no locale: the fastest standard parser
std::optional<int> parse_int(std::string_view s) {
    int value = 0;
    auto [ptr, ec] = std::from_chars(s.data(), s.data() + s.size(), value);
    if (ec != std::errc() || ptr != s.data() + s.size()) {
        return std::nullopt;  // no digits, out of range, or junk after
    }
    return value;
}

int main() {
    for (std::string_view s : {"42", "-17", "42abc", "", "99999999999", " 5", "+5"}) {
        auto n = parse_int(s);
        std::cout << '"' << s << "\" -> ";
        if (n) {
            std::cout << *n << '\n';
        } else {
            std::cout << "no int\n";
        }
    }

    // The raw result tells the failures apart
    std::string_view big = "99999999999";
    int v = 0;
    auto r = std::from_chars(big.data(), big.data() + big.size(), v);
    std::cout << "out of range: " << (r.ec == std::errc::result_out_of_range) << '\n';

    std::string_view junk = "42abc";
    r = std::from_chars(junk.data(), junk.data() + junk.size(), v);
    std::string_view rest(r.ptr, junk.data() + junk.size() - r.ptr);
    std::cout << "read " << v << ", stopped at \"" << rest << "\"\n";

    // Base as the last argument (no 0x prefix allowed)
    std::string_view hex = "ff";
    std::from_chars(hex.data(), hex.data() + hex.size(), v, 16);
    std::cout << "hex ff = " << v << '\n';
}

Output

parse_int accepts "42" and "-17" and returns no int for everything else. It is stricter than std::stoi in two more ways: a leading space (" 5") and a plus sign ("+5") are both rejected, so trim the input first if it may carry spaces (see trimming whitespace). The raw result tells the failures apart: out of range: 1 for the big number, and for "42abc" it reports read 42, stopped at "abc", so you can also use it to read a number off the front of a longer string. The base goes last, and a hex string must not carry a 0x prefix.

4std::istringstream and >>

Before C++11 the usual answer was a string stream: put the text in a std::istringstream and read an int out with >>. It is slower than the functions above and needs more code to be strict, but the same >> works for any type, and it is the natural choice when the string holds several numbers. A failed read sets the stream's fail flag instead of throwing; to reject trailing junk, skip whitespace with std::ws and check that the stream reached the end.

stream_parse.cpp
#include <iostream>
#include <sstream>
#include <string>

// operator>> works for any type; check the stream, then the leftovers
bool read_int(const std::string& s, int& out) {
    std::istringstream in(s);
    in >> out;
    if (in.fail()) {
        return false;
    }
    in >> std::ws;  // allow trailing whitespace only
    return in.eof();
}

int main() {
    for (std::string s : {"42", "  -7  ", "42abc", "abc", "99999999999"}) {
        int n = -1;
        bool ok = read_int(s, n);
        std::cout << '"' << s << "\" ok=" << ok << " n=" << n << '\n';
    }

    // A stream also reads many numbers in a row
    std::istringstream nums("3 14 15 92");
    int sum = 0;
    int x = 0;
    while (nums >> x) {
        sum += x;
    }
    std::cout << "sum " << sum << '\n';
}

Output

" -7 " passes because spaces on both sides are skipped. "42abc" is rejected by the end check, but look at the output: ok=0 n=42. The read itself succeeded and wrote 42 before the helper saw the junk, so don't use n when the result is false. Since C++11 a failed read also overwrites the variable: "abc" leaves n=0 and the overflow leaves n=2147483647, the largest int. Reading in a loop, while (nums >> x), sums "3 14 15 92" to sum 124; to split on something other than whitespace first, see splitting a string.

5The C functions: atoi and strtol

std::atoi from <cstdlib> is still all over older code, usually as atoi(s.c_str()). Its problem is that it has no way to report an error: text that isn't a number returns 0, the same as "0", and a number too big for an int is undefined behaviour. std::strtol is the C function that does report: it sets an end pointer to the first unused character and errno to ERANGE on overflow. std::stoi is built on it and turns those checks into exceptions.

c_functions.cpp
#include <cerrno>
#include <climits>
#include <cstdlib>
#include <iostream>
#include <string>

int main() {
    // atoi: 0 for garbage, so "0" and "abc" look the same
    std::cout << std::atoi("42") << ' ' << std::atoi("0") << ' '
              << std::atoi("abc") << ' ' << std::atoi("42abc") << '\n';

    // strtol reports where it stopped and sets errno on overflow
    std::string inputs[] = {"42", "abc", "42abc", "99999999999999999999"};
    for (const std::string& s : inputs) {
        const char* begin = s.c_str();
        char* end = nullptr;
        errno = 0;
        long v = std::strtol(begin, &end, 10);
        std::cout << '"' << s << "\" -> ";
        if (end == begin) {
            std::cout << "no digits\n";
        } else if (errno == ERANGE) {
            std::cout << "out of range, clamped to LONG_MAX: " << (v == LONG_MAX) << '\n';
        } else if (*end != '\0') {
            std::cout << v << ", then junk \"" << end << "\"\n";
        } else {
            std::cout << v << '\n';
        }
    }
}

Output

The atoi line prints 42 0 0 42: the real zero and "abc" can't be told apart, and "42abc" is accepted as 42. strtol separates all four cases: no digits, 42, then junk "abc", and an overflow that returns LONG_MAX with errno set. Note that it returns a long, so a value in range for long but not for int still needs its own check. In new C++ code there is no reason to pick either over std::stoi or std::from_chars.

6A char to an int

The other half of the question: you have one char, such as a digit taken from a string, and want its value. Casting it to int gives the character code, not the digit. The standard guarantees that '0' to '9' are consecutive, so subtracting '0' gives the digit's value on every system. Check the character with std::isdigit first, and pass it as unsigned char: a negative char value is undefined behaviour for the <cctype> functions.

char_to_int.cpp
#include <cctype>
#include <iostream>
#include <string>

int main() {
    char c = '7';

    // A char is a small integer holding the character code
    std::cout << "int('7') = " << static_cast<int>(c) << '\n';

    // Digits '0'..'9' are guaranteed consecutive, so subtract '0'
    int digit = c - '0';
    std::cout << "'7' - '0' = " << digit << '\n';

    // Check first: std::isdigit needs an unsigned char value
    for (char ch : {'4', 'x', ' '}) {
        if (std::isdigit(static_cast<unsigned char>(ch))) {
            std::cout << '\'' << ch << "' is the digit " << ch - '0' << '\n';
        } else {
            std::cout << '\'' << ch << "' is not a digit\n";
        }
    }

    // Sum the digits of a string
    std::string s = "2026";
    int sum = 0;
    for (char ch : s) {
        sum += ch - '0';
    }
    std::cout << "digit sum of " << s << " = " << sum << '\n';

    // One char as a string: std::stoi(std::string(1, c))
    std::cout << std::stoi(std::string(1, 'f'), nullptr, 16) << '\n';
}

Output

int('7') = 55 is the character code, while '7' - '0' = 7 is the digit. The same subtraction sums the digits of "2026" to 10. For a hex digit like 'f', the subtraction trick doesn't work; wrap the char in a one-character string and use std::stoi with base 16, which prints 15. Going the other way, from a number to text, is covered in converting an int to a string.

7Which should you use?

MethodOn bad input"42abc"Best for
std::stoi(s)Throws42 (check pos)Most code: simple and safe
std::from_charsError codeDetectable via ptrStrict or fast parsing, no exceptions
istringstream >> nFail flag42 (check eof)Several numbers in one string
std::strtolEnd pointer, errnoDetectable via endC APIs and old code
std::atoiReturns 0, overflow is UB42, silentlyAvoid: errors are invisible
c - '0'No checkn/aOne digit char, after std::isdigit

Frequently asked questions

Why does std::stoi("42abc") return 42 instead of throwing?

std::stoi reads as many digits as it can and stops at the first character it cannot use; it throws std::invalid_argument only when there are no digits at all. To reject trailing characters, pass the address of a std::size_t as the second argument and check that it equals s.size(), or use std::from_chars and check that ptr reached the end of the input.

What is the difference between atoi and stoi?

std::atoi is the C function: it takes a const char*, returns 0 for text that is not a number (so you cannot tell it from a real zero) and has undefined behaviour when the value does not fit. std::stoi takes a std::string, throws std::invalid_argument or std::out_of_range instead, and accepts a base and a position argument. Both ignore characters after the digits.

How do I convert a string to an int without exceptions in C++?

Use std::from_chars from <charconv> (C++17): auto [ptr, ec] = std::from_chars(s.data(), s.data() + s.size(), value);. It sets ec to std::errc::invalid_argument or std::errc::result_out_of_range instead of throwing, and ptr shows where it stopped. Unlike std::stoi, it does not skip leading whitespace or accept a + sign.

How do I convert a char to an int in C++?

For a digit character, subtract '0': int d = c - '0'; turns '7' into 7, because the digits 0 to 9 are consecutive in every character set C++ allows. static_cast<int>(c) gives the character code instead (55 for '7'). Check with std::isdigit(static_cast<unsigned char>(c)) first if the char may not be a digit.

How do I convert a string to a long long or an unsigned int?

Use the sibling functions: std::stol, std::stoll, std::stoul and std::stoull work exactly like std::stoi for long, long long, unsigned long and unsigned long long. There is no stou; for an unsigned int, call std::stoul and range-check the result. std::from_chars is a template, so it parses straight into whatever integer type you pass.

How do I convert a string to a double in C++?

Use std::stod (or std::stof, std::stold), which work like std::stoi: leading whitespace is skipped, bad input throws, and the optional second argument reports how many characters were used. std::from_chars also has floating-point overloads in GCC 11 and later. Note that std::stoi("3.99") returns 3, not 4: it stops at the dot.

Run it yourself

Open any of these in the full C++ editor to tweak, run and share.

C++ playground