C++ String to int Conversion
To convert a C++ string to an integer, you can use the std::stoi
function. Here's a step-by-step explanation of how this conversion works:
Include the necessary header file:
#include <string>
Declare a string variable to hold the input:
std::string str = "123";
Use the
std::stoi
function to convert the string to an integer:int num = std::stoi(str);
The std::stoi
function takes a string as its argument and returns an integer. It parses the string and converts it to an integer value. If the string cannot be converted to an integer, it will throw an std::invalid_argument
or std::out_of_range
exception.
If you want to handle the exception, you can use a try-catch
block:
try {
int num = std::stoi(str);
// Use the converted integer
}
catch (const std::exception& e) {
// Handle the exception
}
- Use the converted integer as needed:
std::cout << num << std::endl;
This will output the converted integer to the console.
That's it! You have successfully converted a C++ string to an integer using the std::stoi
function. Let me know if you need further assistance!