how to convert a numeral string to an int in cpp code example
Example 1: string to int in c++
#include <iostream>
#include <string>
using namespace std;
int main() {
string s = "10";
try
{
int i = stoi(s);
cout << i << '\n';
}
catch (invalid_argument const &e)
{
cout << "Bad input: std::invalid_argument thrown" << '\n';
}
catch (out_of_range const &e)
{
cout << "Integer overflow: std::out_of_range thrown" << '\n';
}
return 0;
}
Example 2: c++ string to int
#include <iostream>
#include <string>
int main() {
std::string str = "123";
int num;
num = std::stoi(str);
std::cout << num;
return 0;
}