C++ String::stoi() function
The C++ std::string::stoi() function is used to convert a string to an integer (int). This function analyse the initial characters of the string as an integer and stops at the first non-numeric character. If the conversion is successful, it return the integer value, otherwise it throws an invalid_argument exception.
Syntax
Following is the syntax for std::string::stoi() function.
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
This function has two parameters as described below.
- str − It indicates the string object with the representation of a integral number.
- idx − It indicates the pointer to an object of type size_t, whose value is set by the function to position of the next character in str after the numerical value.
- base − It indicates the numerical base that determines the valid character and their interpretation.
Return value
It returns a integer value of the parsed string.
Example 1
Following is the basic example for the basic conversion to demonstrate the string::stoi using C++.
#include <iostream>
#include <string>
using namespace std;
int main() {
string s = "42";
int num = stoi(s);
cout << num << endl;
return 0;
}
Output
If we run the above code it will generate the following output.
42
Example 2
In this example, we are handling Hexadecimal and Binary strings for integer conversion.
#include <iostream>
#include <string>
using namespace std;
int main() {
string hexStr = "2A";
string binStr = "101010";
int numHex = stoi(hexStr, nullptr, 16);
int numBin = stoi(binStr, nullptr, 2);
cout << numHex << ", " << numBin << endl;
return 0;
}
Output
If we run the above code it will generate the following output.
42, 42
Example 3
In the below example, we are extracting numbers from mixed strings.
#include <iostream>
#include <string>
using namespace std;
int main() {
string mixedStr = "Year2024";
int year = stoi(mixedStr.substr(4));
cout << year << endl;
return 0;
}
Output
Following is the output of the above code.
2024
Example 4
Following is an another example to demonstrate the string:stoi() function. Here the string is passed but that does not contains any valid digit i. e. the numeric value. so, it raises an invalid_argument exception.
#include <iostream>
#include <string>
using namespace std;
int main() {
string invalidStr = "Tutorialspoint";
try {
int num = stoi(invalidStr);
} catch (const std::invalid_argument & e) {
cout << "Invalid input: " << e.what() << endl;
}
return 0;
}
Output
Following is the output of the above code.
Invalid input: stoi
string.htm