StarSweeper StarSweeper - 1 month ago 16
C++ Question

How can I check if string input is convertible to int using std::stoi() in C++?

Background:

I have an input validation function which is supposed to input a string and if it can be converted to an int, do that, but if not print an error.

Code Snippet/What I've tried:

This is what I've tried, but it doesn't work and I get the message "Unhandled exception at .... std::invalid_argument at memory location...."

string response;
cin >> response;

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


Question:

Is there a way to check if string input is convertible to int using
std::stoi()
in C++? Specifically, how can I check to see if an invalid_argument exception will be thrown?


Another 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