String to Int in C++: Safe Conversion Methods

How-to basics · Updated November 22, 2026

In C++, the usual string-to-integer function is std::stoi, declared in <string> and available since C++11. For C++17 and later, std::from_chars is a useful alternative when you want a fast, non-throwing conversion and precise control over whether the entire string was consumed.

The Quick Answer: Use std::stoi

For a basic decimal conversion, pass a std::string to std::stoi:

#include <string>

int number = std::stoi("123");

The result is the integer 123. The function also accepts a std::string variable and a const char*. Include <string> and qualify the function with std::, unless your code has another explicit way to bring it into scope.

This one-line form is convenient when the input is known to contain a valid, in-range decimal number. When input comes from a person, a file, or a network request, handle conversion errors and decide whether extra characters or whitespace should be accepted.

How std::stoi Works

std::stoi converts the initial part of its input that can be read as an integer. By default, it uses base 10. It permits leading whitespace and an optional plus or minus sign, so strings such as " +27" convert to 27 and "-8" converts to -8.

There are two optional parameters: a pointer to a position and a number base. The position parameter tells you how many characters were used in the conversion. This matters because std::stoi("42kg") returns 42 rather than rejecting the entire string. You can check the position to enforce a whole-string rule:

std::string text = "42kg";
std::size_t used = 0;
int value = std::stoi(text, &used);

if (used != text.size()) {
    // The input contained characters after the number.
}

Here, value is 42 and used is 2. Leading whitespace that the conversion skips is included in the consumed portion. Trailing whitespace, however, remains after the number, so a strict check like this rejects it. If your input policy allows trailing spaces, trim them first or explicitly permit whitespace after the parsed number.

The third parameter selects a base from 2 through 36, or 0 for automatic base detection. For example, std::stoi("101", nullptr, 2) returns decimal 5. With base zero, prefixes can signal a base, such as 0x for hexadecimal; a leading zero can indicate octal. Use an explicit base when the expected format is known, since automatic detection may interpret a value differently than a reader expects.

Handle Invalid Input and Out-of-Range Values

std::stoi reports failure with exceptions rather than a special error return value. It throws std::invalid_argument if it cannot parse any integer, and std::out_of_range if the parsed value cannot fit in an int. Catch these when malformed input is an expected possibility, rather than allowing an exception to terminate a program unexpectedly.

try {
    int value = std::stoi(text);
    // Use value here.
} catch (const std::invalid_argument&) {
    // No integer could be parsed.
} catch (const std::out_of_range&) {
    // The parsed number does not fit in an int.
}

This example assumes text is a std::string. Add the relevant standard headers, including <string> and <stdexcept>. If you also need to reject inputs like "12cats", use the position parameter and check it after conversion; successful parsing alone does not mean every character was valid.

For user-facing programs, it is often clearer to put conversion in a small helper that returns a success indicator and writes the result through an output parameter. That keeps exception handling near the input boundary and lets the rest of the program work with a known-valid integer. Choose the helper’s rules deliberately: whether to allow whitespace, a leading plus sign, or trailing characters is a format decision, not something the word “integer” settles on its own.

Use std::from_chars for C++17 and Later

std::from_chars, declared in <charconv>, provides another option for integer parsing in C++17 and later. Unlike std::stoi, it does not throw for ordinary parse failures. It returns a result containing an error code and a pointer to the first character it did not consume. That makes it straightforward to distinguish invalid input, overflow, and extra characters.

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

std::string text = "123";
int value = 0;
auto result = std::from_chars(text.data(), text.data() + text.size(), value);

if (result.ec == std::errc{}) {
    if (result.ptr == text.data() + text.size()) {
        // The entire string was a valid int.
    } else {
        // A valid integer was followed by extra characters.
    }
} else if (result.ec == std::errc::invalid_argument) {
    // No integer could be parsed.
} else if (result.ec == std::errc::result_out_of_range) {
    // The value does not fit in an int.
}

The example uses the string’s character range, from its first character up to—but not including—the end pointer. On successful conversion, result.ptr identifies where parsing stopped. Check that pointer against the end if the whole input must be numeric. For example, the input "123x" can parse the numeric prefix, but the pointer check reveals the remaining x.

There are behavioral differences to remember. Integer from_chars does not skip leading whitespace, and its sign handling does not accept a leading plus sign. If your input may contain either, trim or normalize it first, or choose std::stoi if its parsing rules fit. from_chars is locale-independent and does not allocate memory for the conversion, which makes it attractive in performance-sensitive parsing and code that prefers explicit error handling.

Choosing the Right Conversion Function

The best function depends on the input format, the C++ standard in use, and how you want errors reported. A practical guide is:

  • Use std::stoi for straightforward conversions in C++11 or newer, especially when its whitespace and sign behavior is helpful and exceptions are acceptable.
  • Use std::from_chars for C++17 or newer when you want non-throwing error reporting, explicit full-input validation, or efficient parsing of character ranges.
  • Use std::stol or std::stoll when the target type should be long or long long, respectively. These functions still need range and input validation.
  • Use a stream when you are already parsing structured input with stream operations and its formatting behavior suits the task.

Check your compiler’s selected language standard and standard-library support, especially if building with an older toolchain. A compiler may support a modern language mode while relying on a library version with incomplete features, or the project may be configured for an older standard. For ordinary integers, std::from_chars is standardized for C++17; floating-point overload availability has had different implementation histories, but that does not affect the integer example above.

Common Problems and Misconceptions

“It returned a number, so the whole string was valid.” Not necessarily. std::stoi and std::from_chars can parse a numeric prefix and leave a suffix unconsumed. Check the position or returned pointer when extra characters must be rejected. This distinction is useful for strict input validation, such as reading an ID that must contain digits only.

“Zero means conversion failed.” Zero is a valid integer, so it cannot serve as a reliable error signal. std::stoi("0") legitimately returns zero. Use exceptions or the result fields from from_chars to detect failure instead.

“The conversion checks whether the value fits my destination type.” std::stoi specifically produces an int. If the value is too large for that type, it throws; it does not automatically choose a wider type. If your data can exceed the range of int, parse into an appropriate wider type and still check its limits. The exact width of standard integer types can vary by platform, so do not assume every type has the same range everywhere.

“A number with a decimal point will be rounded.” Integer conversion is not decimal rounding. With std::stoi("3.9"), the integer prefix can be parsed as 3, with the period and remaining characters left unconsumed. If decimal input is intended, parse it as a floating-point value and define an explicit rounding or truncation policy.

Another common issue is assuming all whitespace is treated identically by all conversion methods. std::stoi accepts leading whitespace, while from_chars does not. Also, a valid conversion does not make untrusted input safe for every later use: validate limits and meaning for the application, such as ensuring a parsed quantity is positive before using it as a count.

Other Options: atoi, Streams, and C Functions

std::atoi is an older C-style function available through <cstdlib>. It converts a character string to an integer but does not provide a reliable way to distinguish invalid input from a valid zero, and it is a poor choice when range errors must be handled safely. Prefer std::stoi or std::from_chars for new C++ code where input may be invalid.

A string stream can parse an integer with the extraction operator, as in std::istringstream stream(text); stream >> value;. Check the stream state to find extraction failures. If the input must contain only one integer, you must also check for remaining non-whitespace characters; successful extraction alone may only mean that an integer prefix was read. Streams can be convenient when parsing several fields or mixing numbers and other formatted data, but are more machinery than a simple conversion requires.

The C library function std::strtol is another option when you need its end-pointer and range-reporting behavior, including in code that interfaces with C APIs. It requires more deliberate error checking, including examining the end pointer and range status. For typical modern C++ code, std::stoi offers a simpler throwing interface, while std::from_chars offers a compact non-throwing one.

Frequently Asked Questions

What is the simplest string-to-int function in C++?
std::stoi is the simplest common choice: include <string> and call std::stoi(text). Catch its exceptions if the input might be invalid or outside the range of int.

Does std::stoi accept negative numbers?
Yes. It accepts an optional minus sign, so std::stoi("-25") returns -25, provided the value fits in an int. It also accepts an optional leading plus sign.

How do I make std::stoi reject extra characters?
Pass a pointer to a std::size_t variable as the second argument, then compare the resulting position with the string’s length. A mismatch means some characters were not consumed. Decide separately whether trailing whitespace should be permitted.

Can I convert a string to an int without exceptions?
In C++17 and later, use integer std::from_chars. Check its ec member for invalid input or an out-of-range value, and compare ptr with the end of the input to require a complete match.

What happens if the number is too large for int?
std::stoi throws std::out_of_range. With std::from_chars, the error code is std::errc::result_out_of_range. If larger values are valid for your program, use a wider integer type and validate against that type’s range.

Related

Try it: the Date Difference Calculator: days, months, years and weekdays between two dates, with the DATEDIF formulas.

More in How-to basics

Sources: Function behaviour and menu paths: Microsoft Support documentation for Excel. Method & sources

Spotted an error in this guide? Let us know.