StarSweeper StarSweeper - 3 days ago 5
C++ Question

How do I validate int input using std::stoi() in C++?

Is there a way to check if string input is convertible to int using

std::stoi()
in C++? (For example, could I check to see if an invalid_argument exception will be thrown?)


An example that doesn't work, but hopefully explains what I'm trying to do:

string response;
cout << prompt;

if (std::stoi(response) throws invalid_argument) { //Something like this
return std::stoi(response);
}
else {
badInput = true;
cout << "Invalid input. Please try again!\n";
}


Research:

I've found several ways to check if a string is an int, but I'm hoping there is a way to do it using
std::stoi()
which I haven't been able to find yet.

Answer

You should catch the exception when it is thrown, rather than trying to predetermine whether or not it will be thrown.

string response; 
cin >> response;

try {
    return std::stoi(response);
}
catch (...) {
    badInput = true;
    cout << "Invalid input. Please try again!\n";
}
Comments