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.
SyntaxFollowing 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.
It returns a integer value of the parsed string.
Example 1Following 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.
42Example 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, 42Example 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.
2024Example 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
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4