c++ string to int
To convert a string to an int in C++, you can use the stoi()
function. Here are the steps to do this conversion:
Include the necessary header file:
#include <string>
Declare a string variable to hold the input string:
std::string inputString;
Prompt the user to enter a string:
std::cout << "Enter a string: ";
Read the input string from the user:
std::cin >> inputString;
Declare an integer variable to hold the converted value:
int convertedInt;
Use the
stoi()
function to convert the string to an int:convertedInt = std::stoi(inputString);
Handle any exceptions that might occur during the conversion. The
stoi()
function throws anstd::invalid_argument
exception if the input string does not represent a valid integer.Use the converted integer as needed in your program.
That's it! Following these steps will allow you to convert a string to an int in C++.