The stoi function is a built-in function in the C++ standard library that transforms a string into an integer value. This abbreviation represents "string to integer". When provided with a string input, it outputs the integer equivalent. In cases where the input string does not depict a legitimate integer, the function has the capability to throw an exception of type std::invalid_argument.
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 one instance, the character sequence "123" undergoes a transformation to become the numerical value 123. In another instance, the string "-456" is transformed into the integer -456. However, when attempting to convert the string "7.89" to an integer, an exception of std::invalid_argument type is raised due to its invalid format.
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 initial illustration transforms the string "100" into the integer value 100. In the subsequent instance, the string "200" undergoes conversion to the hexadecimal integer 512 by specifying 0 as the second parameter and 16 as the third parameter in the stoi function.
In the third scenario, the value "300" is transformed into the octal integer 192 by providing nullptr as the second parameter and 8 as the third argument to the stoi function.
In the fourth case, the character sequence "abc" does not qualify as a legitimate integer, leading to the triggering of a std::invalid_argument exception.