string in int in cpp
To convert a string to an int in C++, you can use the std::stoi
function. Here are the steps involved:
- Include the necessary header file: To use the
std::stoi
function, you need to include the<string>
header file in your code.
cpp
#include <string>
- Declare a string variable: Declare a string variable that holds the string value you want to convert to an int.
cpp
std::string str = "12345";
- Call the
std::stoi
function: Pass the string variable as an argument to thestd::stoi
function. This function converts the string to an int.
cpp
int num = std::stoi(str);
The std::stoi
function parses the string starting from the beginning and converts it to an int until it encounters a non-digit character. If the string cannot be converted to an int, an exception of type std::invalid_argument
or std::out_of_range
is thrown.
- Use the converted int: The converted int value can now be used in your code.
cpp
std::cout << "The converted int is: " << num << std::endl;
This will output: "The converted int is: 12345".
That's it! You have successfully converted a string to an int in C++ using the std::stoi
function.