There are a ton of functions I see that says "Throw an exception if fail", or something along that line.
IE. If no conversion could be performed, an invalid_argument exception is thrown.--Stoi
I'm wondering how to use this invalid_argument. I've tried reading the page on invalid_argument and exceptions, but to be honest, I feel more lost after reading them.
So for example, if I were to use stoi and take in a user input string, and convert it to int. If it cannot be converted, how do I tell the computer to detect it and ask the user to input again?
1 2 3 4 5 6 7 8 9 10 11 12
IE
#include <iostream>
usingnamespace std;
void main(){
string userinput;
int userinputINT = stoi(userinput);
//code here to detect if stoi fails
}
#include <iostream>
#include <stdexcept>
int main() {
std::string userinput, userinput2;
int result, result2;
while (true) {
try {
std::cin >> userinput >> userinput2;
result = std::stoi(userinput);
result2 = std::stoi(userinput2);
break; // get out of the while loop
} catch (const std::invalid_argument& ia) {
std::cerr << "Invalid Argument: " << ia.what() << "\n";
std::cerr << "Please try again: "
// it should now loop around until no exception is thrown:
}
}
//...
return 0;
}