Reputation: 417
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.
Upvotes: 3
Views: 12780
Reputation: 20671
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";
}
Upvotes: 4
Reputation: 2181
std::stoi converts as much as possible, and only throws an exception if there is nothing to convert. However, std::stoi accepts a pointer parameter representing the start index, which is updated to the character that terminated conversion. See MSDN stoi docs here.
You can use stoi to test by passing 0 as the starting index, then verifying that the returned index is the same as the total length of the string.
Treat the following as pseudo-code, it should give you an idea of how to make it work, assuming response is a std::string:
std::size_t index = 0;
auto result = std::stoi(response, &index);
if(index == response.length()){
// successful conversion
return result;
}
else{
// something in the string stopped the conversion, at index
}
Upvotes: -1
Reputation: 165
std::stoi()
throws an exception if conversion could not be performed.
Look at the "Exceptions" section in this c++ documentation
http://www.cplusplus.com/reference/string/stoi/
Upvotes: 0