String to Number Function in C++

Formulas & functions · Updated November 23, 2026

The primary function to convert a string to a number in C++ is std::stoi (string to int), with siblings std::stol, std::stoll, std::stof, std::stod, and std::stold for other numeric types. These functions are declared in the <string> header and are the modern, recommended way to parse numeric strings in C++11 and later.

Background: Why C++ Has Several Conversion Methods

C++ inherited C’s atoi, atol, atof, and strtol family, but these have limitations: atoi silently returns 0 on error, and strtol requires manual pointer handling to detect invalid input. The C++ standard library added std::stoi and its relatives in C++11 to provide type-safe, exception-based error handling. There is also std::from_chars (C++17) for high-performance, locale-independent parsing, and std::stringstream for flexible but slower conversions. Each method has its own trade-offs in speed, error detection, and support for leading/trailing whitespace.

How std::stoi and Its Variants Work

All std::stoi-style functions take a string, an optional pointer to a size_t to receive the index of the first unconverted character, and an optional integer base (default 10). For example:

#include <string>
#include <iostream>

int main() {
    std::string s = "42";
    int n = std::stoi(s);
    std::cout << n; // prints 42
}

For floating-point conversions, std::stof and std::stod do not take a base parameter. The functions skip leading whitespace, then parse an optional sign, digits, and for floating-point, a decimal point and exponent. If no conversion can be performed, they throw std::invalid_argument; if the value is out of range, they throw std::out_of_range.

Choosing the Right Conversion Function

Your choice depends on the target type and error-handling needs:

  • Integer types: Use std::stoi (int), std::stol (long), std::stoll (long long).
  • Unsigned integers: Use std::stoul and std::stoull.
  • Floating-point: Use std::stof (float), std::stod (double), std::stold (long double).
  • Performance-critical code: Use std::from_chars (C++17) for integers and floating-point; it is faster and does not throw or allocate.
  • Legacy or C-style code: Use strtol or strtod if you need to stay C-compatible.

If you need to parse a string that may contain trailing non-numeric characters, pass a pointer to a size_t to get the position where parsing stopped, then check if it equals the string length.

Common Pitfalls and How to Avoid Them

One frequent mistake is assuming std::stoi accepts leading/trailing whitespace. It does skip leading whitespace, but it does not skip trailing whitespace—if the string is “42 “, std::stoi will convert 42 and set the index to 2, leaving the space unconverted. Another pitfall is not catching exceptions. Always wrap conversion in a try-catch block if the input might be invalid:

try {
    int n = std::stoi(user_input);
} catch (const std::invalid_argument&) {
    // handle non-numeric input
} catch (const std::out_of_range&) {
    // handle number too large or too small
}

Also, be aware that std::stoi accepts a base parameter; if you pass 0, it auto-detects the base from the prefix (e.g., “0x” for hex, “0” for octal). This can lead to surprising results if you forget to specify base 10.

Comparison: std::stoi vs. std::from_chars vs. stringstream

std::stoi is simple and safe, but it throws exceptions and may allocate memory for the string internally. std::from_chars is the fastest and most low-level: it does not throw, does not allocate, and does not skip whitespace (you must skip it yourself). Example:

#include <charconv>
#include <string>

std::string s = "123";
int n;
auto [ptr, ec] = std::from_chars(s.data(), s.data() + s.size(), n);
if (ec == std::errc()) {
    // success, n is 123
}

std::stringstream is the most flexible but slowest; it supports formatting and locales, but for simple conversions it is overkill. In practice, use std::stoi for clarity, std::from_chars for performance, and stringstream only when you need to parse mixed content.

Handling Errors and Edge Cases

When converting, always consider these edge cases:

  • Empty string: std::stoi throws std::invalid_argument.
  • Leading plus/minus: “+42” and “-42” are valid; “++42” is not.
  • Hexadecimal: Use base 16, e.g., std::stoi("1A", nullptr, 16) yields 26.
  • Underscores or commas: Not allowed; only digits and sign are parsed.
  • Locale: std::stoi uses the current C++ locale, which may affect decimal point in floating-point conversions. std::from_chars is locale-independent.

For floating-point, std::stod accepts “inf”, “infinity”, and “nan” (case-insensitive) as valid input, which can be surprising.

Performance Considerations

If you are converting millions of numbers, std::from_chars is typically 2-5 times faster than std::stoi because it avoids exception overhead and locale checks. However, std::from_chars for floating-point is only available in some standard library implementations (e.g., MSVC, GCC 11+). For integers, it is widely supported. If you need maximum portability, stick with std::stoi.

Frequently Asked Questions

Can I convert a std::string to a double in C++? Yes, use std::stod. For example, double d = std::stod("3.14"); works. It throws std::invalid_argument if the string is not a valid floating-point number.

What is the difference between std::stoi and atoi? atoi returns 0 on error and does not detect out-of-range values; std::stoi throws exceptions and gives you a way to know where parsing stopped. Always prefer std::stoi in C++ code.

How do I convert a string to an int without exceptions? Use std::from_chars (C++17) or check the string manually before calling std::stoi. For example, you can verify that the string contains only digits (and an optional sign) before conversion.

Does std::stoi handle leading zeros? Yes, it treats “042” as decimal 42, unless you specify base 8 or 0. With base 0, “042” would be interpreted as octal (34).

Can I convert a string with commas like “1,000” to an integer? No, std::stoi does not handle thousands separators. You need to remove commas manually or use a custom parser.

Is there a function to convert a string to a float in C++11? Yes, std::stof converts to float, std::stod to double, and std::stold to long double. They all behave similarly to std::stoi but for floating-point types.

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.