STOI()
This function converts a string to an integer. It stands for "string to integer." The function takes a std::string
(or C-style string) as input and returns its integer equivalent. It also allows optional parameters to specify the starting position for the conversion and to store the position of the first character not used in the conversion. If the string cannot be converted to a valid integer (due to invalid characters or overflow), stoi()
throws exceptions such as std::invalid_argument
or std::out_of_range
. This function is very useful for parsing numbers from strings in user input or file processing.
//SYNTAX
int number = stoi(stringValue); // Convert string to int
#include <iostream> // For input and output
using namespace std;
int main() {
string intString = "42"; // String representing an integer
string floatString = "3.14"; // String representing a float
int number = stoi(intString); // Convert to int
float decimal = stof(floatString); // Convert to float
cout << "Integer: " << number << endl;
cout << "Float: " << decimal << endl;
return 0; // End of program
}
OUTPUT:
Integer: 42
Float: 3.14
Last updated