The stoi is a C++ standard library function that converts a string to an integer. It stands for "string to integer" . It takes a string as input and returns the corresponding integer value. The function can raise an exception of type std::invalid_argument if the input string does not represent a valid integer.
Examples of using stoi in C++:
#include <iostream>
#include <string>
int main() {
std::string str1 = "123";
int num1 = std::stoi(str1);
std::cout<< num1 << std::endl; // Output: 123
std::string str2 = "-456";
int num2 = std::stoi(str2);
std::cout<< num2 << std::endl; // Output: -456
std::string str3 = "7.89";
try {
int num3 = std::stoi(str3);
} catch (std::invalid_argument&e) {
std::cout<< "Invalid argument: " << str3 << std::endl;
}
return 0;
}
Output
123
-456
In the first example, the string "123" is converted to the integer 123 . In the second example, the string "-456" is converted to the integer -456 . In the third example, the string "7.89" is not a valid integer, so a std::invalid_argument exception is thrown.
Other example code snippet:
#include <iostream>
#include <string>
int main() {
std::string str1 = "100";
int num1 = std::stoi(str1);
std::cout<< num1 << std::endl; // Output: 100
std::string str2 = "200";
int num2 = std::stoi(str2, 0, 16);
std::cout<< num2 << std::endl; // Output: 512
std::string str3 = "300";
int num3 = std::stoi(str3, nullptr, 8);
std::cout<< num3 << std::endl; // Output: 192
std::string str4 = "abc";
try {
int num4 = std::stoi(str4);
} catch (std::invalid_argument&e) {
std::cout<< "Invalid argument: " << str4 << std::endl;
}
return 0;
}
Output
100
512
192
Invalid argument: abc
The first example converts the string "100" to the decimal integer 100 . In the second example, the string "200" is converted to the hexadecimal integer 512 by passing 0 as the second argument and 16 as the third argument to stoi .
In the third example, the string "300" is converted to the octal integer 192 by passing nullptr as the second argument and 8 as the third argument to stoi.
In the fourth example, the string "abc" is not a valid integer, so a std::invalid_argument exception is thrown.