In C++, use std::stoi to convert a string to an int; it is declared in the <string> header. For example, int value = std::stoi("123"); produces the integer 123. If you need to reject invalid input reliably or avoid exceptions, C++17 also provides std::from_chars.
The Basic Conversion Function: std::stoi
std::stoi is the standard C++ function most directly suited to converting a string to an integer. Its name means “string to integer,” and it has been available since C++11. Include <string> and call it in the std namespace. The simplest form takes a string and uses base 10:
#include <string>
std::string text = "256";
int number = std::stoi(text);
The function accepts a std::string (or a C-style null-terminated character string that can be converted to one) and returns an int. It can also take a pointer to a position value and a number base. Those optional arguments are useful when the input may contain more than a number or when it uses a base other than decimal.
Use std::stoi when you want a straightforward conversion and can handle its exceptions. It is not a function that silently guarantees the entire input is a valid integer: by default, it can successfully convert the numeric prefix of a longer string. That behavior is often useful, but it needs attention when validating user input or file data.
A Complete Example with Input Checking
This example converts a decimal string, checks whether every character was consumed, and handles the two main conversion exceptions:
#include <string>
#include <stdexcept>
#include <iostream>
int main() {
std::string text = " -42";
try {
std::size_t used = 0;
int value = std::stoi(text, &used, 10);
if (used != text.size()) {
std::cerr << "Input contains extra characters\n";
return 1;
}
std::cout << value << '\n';
} catch (const std::invalid_argument&) {
std::cerr << "Input does not start with an integer\n";
return 1;
} catch (const std::out_of_range&) {
std::cerr << "Integer is outside the range of int\n";
return 1;
}
}
The position output counts the characters consumed from the beginning, including leading whitespace that the conversion accepts. In this example, the complete string is valid, so used matches text.size() and the program prints -42. If the string were 42cats, conversion would produce 42, but the position check would detect the remaining characters.
How std::stoi Parses a String
For base 10, std::stoi skips leading whitespace, accepts an optional plus or minus sign, and reads digits until it reaches a character that is not part of the number. It does not require the rest of the string to be empty. Thus std::stoi(" +73kg") returns 73; if you pass a position pointer, it reports where parsing stopped.
The third argument selects the number base. You can specify a base from 2 through 36, where letters represent digit values above 9. For example, base 2 uses only 0 and 1, while base 16 uses digits 0–9 and letters A–F (case-insensitively). A base of 10 is the default.
Passing base 0 asks the function to infer the base using conventional prefixes: a leading 0x or 0X indicates hexadecimal, and a leading zero indicates octal; otherwise parsing is decimal. This can surprise readers: std::stoi("010", nullptr, 0) yields 8, not 10. For ordinary decimal input, specify base 10 or leave the default rather than using base 0 without a reason.
std::stoi(text)parses as decimal.std::stoi(text, nullptr, 16)parses as hexadecimal.std::stoi(text, nullptr, 2)parses as binary.std::stoi(text, nullptr, 0)applies prefix-based base detection.
Errors, Ranges, and Partial Input
std::stoi reports conversion failures with exceptions. It throws std::invalid_argument if it cannot parse any integer characters. An empty string or a string such as hello triggers this exception. It throws std::out_of_range if the parsed value cannot be represented as an int. The exact limits of int depend on the implementation, so code should not assume a particular maximum value across every platform.
A frequent mistake is assuming that no exception means the entire input was valid. For example, std::stoi("19.8") returns 19 because the decimal point ends the integer prefix. Check the position argument when trailing characters must be rejected. Decide explicitly whether trailing whitespace is allowed: the consumed position stops before trailing whitespace, so a strict comparison with the string length rejects it. If your input rules allow such whitespace, handle or trim it deliberately rather than accidentally accepting other suffixes.
Another important distinction is the destination type. std::stoi returns an int; it is not appropriate when valid input may exceed the range of that type. C++ provides std::stol for long and std::stoll for long long. These functions have corresponding wide-string forms for std::wstring. Choosing a wider type can help, but even a wide integer has a finite range, so out-of-range handling still matters.
Using std::from_chars Instead
For performance-sensitive code or parsing untrusted text without exceptions, consider std::from_chars, available for integers since C++17 in the <charconv> header. It writes into an integer you provide and returns both a pointer to the stopping position and an error code. It does not allocate a temporary string or throw conversion exceptions.
#include <charconv>
#include <string>
#include <system_error>
std::string text = "314";
int value = 0;
auto result = std::from_chars(text.data(), text.data() + text.size(), value, 10);
if (result.ec == std::errc{} && result.ptr == text.data() + text.size()) {
// The whole string was a valid decimal int.
}
The error code indicates whether conversion succeeded or the input was invalid or out of range. The returned pointer indicates how much was parsed, so checking it against the end is still necessary if the entire input must be consumed. Unlike std::stoi, integer from_chars does not skip leading whitespace. It also does not accept a leading plus sign; a minus sign is accepted for signed destinations. Its base is specified explicitly, with 10 as the default, and base 0 does not request automatic prefix detection.
These differences make from_chars predictable for machine-formatted input, but mean it is not a drop-in replacement in every situation. If input may have surrounding spaces or a plus sign, normalize or validate that input according to your requirements before calling it.
Which Conversion Method Should You Choose?
For many programs, the choice is between convenience and control. Use std::stoi when its whitespace behavior, exceptions, and prefix parsing suit your needs. Use std::from_chars when you want non-throwing status results, explicit range checking, or efficient parsing of character ranges. Both can report where parsing stopped, and neither should be treated as full-string validation unless you check that position.
- Simple application input:
std::stoiis easy to read; catch its exceptions if malformed input is possible. - Strict configuration or protocol data:
std::from_charscan make error handling explicit, followed by a check that the returned pointer reached the end. - Values larger than
int: usestd::stollor parse into an appropriately sized integer withstd::from_chars. - Older language standards:
std::stoirequires C++11, while integerstd::from_charsrequires C++17.
For localized human-readable numbers, neither function automatically provides every locale-specific convention people may expect. For example, thousands separators and locale-specific decimal or digit formats require a deliberate parsing strategy. Avoid guessing a format from the user’s environment when the input is meant to follow a fixed data format.
Common Alternatives and Misconceptions
std::atoi is an older C library function that converts a C-style string to an integer, but it does not provide a reliable way to distinguish invalid input from a valid zero or report range errors. That makes it a poor default for new code that needs validation. The C function strtol offers an end pointer and range reporting, and is useful when working with C-style strings or C interfaces; in modern C++ code, std::stoi or std::from_chars is often clearer.
Also, converting a string to an integer is not the same as converting it to a floating-point value and then casting. A cast from a floating-point number discards its fractional part; it does not validate integer-text syntax. If the input is supposed to contain only whole-number digits, parse it as an integer and validate the complete input.
Frequently Asked Questions
What is the function to convert a string to an integer in C++?
Use std::stoi from <string>. It returns an int and is available from C++11 onward.
How do I convert a string to an integer without exceptions?
In C++17 or later, use integer std::from_chars from <charconv>. Check its error code and, if the whole string must be valid, confirm that its returned pointer reached the end.
Does std::stoi reject letters after the number?
Not by itself. It parses a valid numeric prefix, so std::stoi("25abc") returns 25. Pass a position pointer and compare the consumed position with the input length to reject the suffix.
How do I convert a hexadecimal string to an int?
Call std::stoi(text, nullptr, 16) for base 16. You can also pass a position pointer if you need to confirm that all input characters were consumed.
What is the difference between std::stoi and std::stol?std::stoi returns an int, while std::stol returns a long. Their available numeric ranges depend on the types on the platform, and both can throw std::invalid_argument or std::out_of_range.
Related
- Snowflake SPLIT_PART: Syntax, Examples, and Common Issues
- JavaScript split() Explained: Strings, Limits, and Examples
- Microsoft Access Split Form: How It Works and When to Use It
Try it: the Formula Explainer: paste any formula and see each function and reference in plain English.
More in Formulas & functions
- Excel Conditional Formatting: Nested IFs for Dates?Yes. Excel conditional formatting can use a nested IF formula, but the formula must ultimately return TRUE or…
- Split Cells in Excel: Text to Columns and FormulasTo split text stored in one Excel cell into separate columns, use Data > Text to Columns on…
- Color Picker in Excel: Choose and Match Colors PreciselyIn Excel for Microsoft 365 on Windows, select the cell or range, then go to Home > Fill…
- Excel Timesheet Calculator Formula: Examples and TipsFor an Excel timesheet with start time in B2, end time in C2, and an unpaid break duration…
- CONCAT in Excel: Join Text and NumbersYes. Excel’s CONCAT function can join numbers with text or other values, but it does not preserve a…
- Excel INDEX MATCH With Table Structured ReferencesYes—Excel INDEX MATCH works with table structured references. For example, if a table named Inventory has columns Item…
Sources: Function behaviour and menu paths: Microsoft Support documentation for Excel. Method & sources
Spotted an error in this guide? Let us know.