In C++, std::stoi() reads an int from the beginning of a string.
It skips leading whitespace, then parses an optional sign and digits. Include <string>.
This is a free function from <string> that works with std::string (and sometimes wstring). Member functions like find live on the string object with a dot; helpers like this are called as std::stoi(...).
Syntax
Pass the string; optionally capture where parsing stopped and the base.
C++
int n = std::stoi("42");
int x = std::stoi(" -17");
int h = std::stoi("ff", nullptr, 16);
Call
What it does
std::stoi(str)
Parse str as a base-10 int.
std::stoi(str, &idx, base)
Also store the end index and use base (2..36).
Related: stol, stoll for longer integers; stoul/stoull for unsigned.
Library declarations
C++
int stoi(const string& str, size_t* idx = 0, int base = 10);
int stoi(const wstring& str, size_t* idx = 0, int base = 10);
Parameters
Parameter
Description
str
Input text.
idx
Optional. Receives index of the first unconverted character.
base
Numeric base 2–36, or 0 for auto detect. Default 10.
Return Value
Return Value
Description
int
The parsed value.
C++ Examples
Example 1 — Basic stoi()
Convert a simple number string.
C++
#include <iostream>
#include <string>
int main() {
int n = std::stoi("42");
std::cout << n << '\\n';
return 0;
}
Output
42
How It Works
The text starts with digits.
stoi parses them as base 10.
Result is integer 42.
Example 2 — stoi End Index
See where parsing stopped.
C++
#include <iostream>
#include <string>
int main() {
std::size_t idx = 0;
int n = std::stoi("123abc", &idx);
std::cout << n << ' ' << idx << '\\n';
return 0;
}