String to Integer Function in C++ (stoi, atoi, Stringstream)

Formulas & functions · Updated November 23, 2026

The primary function to convert a string to an integer in C++ is std::stoi (string to int), available in the <string> header since C++11. It parses the string and returns an int value, throwing exceptions on invalid input. For older code or C-style strings, std::atoi (from <cstdlib>) also works but silently returns 0 on failure.

Background: Why Multiple Functions Exist

C++ inherited C’s atoi, which takes a const char* and returns an int. It is simple but unsafe—if the string is not a valid number, it returns 0 with no way to distinguish that from a legitimate “0”. The C++11 standard introduced std::stoi and its siblings (stol, stoll, stof, stod) to work directly with std::string and to report errors via exceptions. There is also std::stringstream from <sstream>, a more flexible but slower method that can handle mixed parsing.

How std::stoi Works

std::stoi takes three optional parameters: the input string, a pointer to store the index of the first unconverted character, and a base (default 10). It skips leading whitespace, accepts an optional sign (+/-), then reads digits until it hits a non-digit. The conversion stops there, and if you provided an index pointer, it gets set to that position.

#include <string>
#include <iostream>

int main() {
    std::string s = "123abc";
    size_t pos = 0;
    int val = std::stoi(s, &pos);
    std::cout << val << " at index " << pos; // 123 at index 3
}

If the string starts with invalid characters (no digits at all), it throws std::invalid_argument. If the resulting value overflows the int range, it throws std::out_of_range.

How to Choose: stoi vs atoi vs stringstream

Your choice depends on the context:

  • Use std::stoi when you have a std::string and need error detection—it’s the default for modern C++.
  • Use std::atoi only for legacy C code or when you’re certain the input is valid and you want a fast, exception-free call. It takes a const char*, so you’d call std::atoi(str.c_str()).
  • Use std::stringstream when you need to parse multiple values from one string or when you’re already using streams. It’s slower but flexible.

Common Problems and Pitfalls

Beginners often trip over these issues:

  • atoi returning 0 on failure—if your string could be “0” or invalid, you can’t tell them apart. Use stoi or check the string first.
  • stoi throwing exceptions—if you don’t catch them, your program terminates. Wrap in try-catch blocks when input is user-provided.
  • Partial conversion—stoi stops at the first non-digit, so “12abc” becomes 12. If you need to reject such strings, check the pos value against the string length.
  • Whitespace—stoi skips leading spaces, but not trailing ones. ” 42 ” works, but “42 ” is fine too (stops at the space).
  • Base confusion—the default base is 10, but if you pass base 0, it uses C-style rules: leading 0 means octal, 0x means hex. This can surprise you.

Comparison of Conversion Methods

Here’s a quick comparison table of the main approaches:

  • std::stoi: C++11+, throws exceptions, handles std::string, fast.
  • std::atoi: C legacy, no exceptions, returns 0 on error, takes const char*, very fast.
  • std::stringstream: C++98+, no exceptions (unless you enable them), slow, can parse multiple values.
  • std::from_chars (C++17, <charconv>): fastest, no exceptions, but only works on const char* ranges and doesn’t handle leading spaces or signs as flexibly. Use for performance-critical code.

Performance and Cost Considerations

If you’re converting millions of strings, performance matters. std::stoi is reasonably fast but has overhead from exception handling machinery (even when no exception is thrown). std::atoi is faster because it does no error checking. std::stringstream is the slowest due to locale and formatting overhead. For maximum speed, std::from_chars is the modern choice—it’s designed to be allocation-free and exception-free, but it requires you to manage the end pointer manually. In most applications, the difference is negligible, so prioritize clarity and safety.

Safety and Error Handling Best Practices

Always assume input can be invalid, especially from user input or file parsing. With std::stoi, catch exceptions:

try {
    int value = std::stoi(input);
    // use value
} catch (const std::invalid_argument&) {
    // handle non-numeric input
} catch (const std::out_of_range&) {
    // handle overflow
}

If you need to reject partial conversions, check the position:

size_t pos = 0;
int value = std::stoi(input, &pos);
if (pos != input.size()) {
    // there are trailing non-digit characters
}

For std::atoi, there’s no way to detect failure, so only use it when the string is guaranteed to be a valid integer (e.g., from a trusted source).

Alternatives for Special Cases

Sometimes you need more than a simple int:

  • Convert to long or long long: use std::stol or std::stoll for larger ranges.
  • Convert to unsigned: there’s no stou in the standard library (it was proposed but not added), so use std::stoul and cast, or use std::from_chars with unsigned type.
  • Parse hexadecimal or binary: pass a base to stoi (e.g., std::stoi("0xFF", nullptr, 16)).
  • Parse with locale support: std::stoi respects the current C++ locale, which can cause issues with thousands separators. Use std::from_chars if you need locale-independent parsing.

Frequently Asked Questions

What’s the difference between stoi and atoi?

The main difference is error handling. stoi throws std::invalid_argument if the string can’t be converted and std::out_of_range if the value overflows. atoi returns 0 in both cases, making it impossible to tell if the input was “0” or invalid. stoi also works directly with std::string and can report the position where parsing stopped.

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

Use std::from_chars (C++17) for a non-throwing, fast conversion. It returns an error code in the result struct. Alternatively, you can manually validate the string with std::isdigit before calling atoi, but that’s error-prone. For most cases, catching exceptions from stoi is fine.

Why does stoi throw std::invalid_argument for an empty string?

Because an empty string contains no digits, so there’s nothing to convert. The standard says it must throw std::invalid_argument. If you want to treat empty strings as 0, check str.empty() first and handle it separately.

Can I use stoi with a char array?

Yes, but you’ll need to convert the char array to a std::string first, or use std::from_chars which works directly on const char* pointers. For example: std::string s(arr); int x = std::stoi(s); or int x; std::from_chars(arr, arr + len, x);.

Is there a function to convert a string to an int in C++98?

No, stoi was introduced in C++11. In C++98, you can use std::stringstream or atoi. For example: std::stringstream ss(str); int x; ss >> x; but this doesn’t detect errors reliably unless you set the failbit.

Related

Try it: the Formula Explainer: paste any formula and see each function and reference in plain English.

More in Formulas & functions

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

Spotted an error in this guide? Let us know.