I am trying to convert a string to an integer using stoi, I have never touched on try catch and don't know how to handle the exception or error given by stoi. The code below is what I've managed to produce but I can't seem to be able to let the user re-enter once the stoi conversion has failed. Shouldn't cin>>input be enough to start the try catch again? Really new to try catch and error handling. I am trying to loop the input for user when stoi conversion fails. Appreciate it if anyone can give me some examples.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
cout<<"Enter the amount of cake"<<endl;
amount_input = stoi(input);
std::cout << "How many slices of cake? ";
getline( std::cin, s );
number_of_slices_of_cake = std::stoi( s );
if (number_of_slices_of_cake < 0) throw 1;
std::cerr << "You must answer with a whole number >= 0.\n";
int number_of_cakes = (number_of_slices_of_cake + 7) / 8;
std::cout << "Great! That's " << number_of_cakes << " cakes!\n";
Notice that on line 13 we also throw if the number of slices is invalid. It does not matter what we throw, since we are just trying to use the same response as a non-integer input. In other words, the catch (...) block catches both the 1 we throw and either of the things that stoi() throws.
If we wanted to have a different complaint then we would do something other than throwing that 1. (Such as complain and quit.)