i am learning about functions and function arguments. i am attempting to right a function called int repeat(int rep){...}
below is the code for the function int repeat()
.
int repeat(int rep){
std::cout << "Do you wish to factorial another number? Y or N: " <<
std::endl;
char c1;
restart:
std::cin >> c1; /* pretend user input is "7". the below if statement should execute the `throw` statement. However it does not evaluate the if statement as true. and passes over it.*/
try{
if (std::cin.fail()){
throw std::runtime_error(" Must enter y for yes or n for no.");
}
if (c1 == 'y' || c1 == 'Y'){
return rep = 1;
}
else{
//system("pause");
return rep = 0;
}
}
catch (std::runtime_error err2){
std::cout << err2.what() << std::endl;
std::cin.clear();
std::cin.ignore();
goto restart;
}
}
the issue in my code appears with the first if statement: if (std::cin.fail()){ throw std::runtime_error(" Must enter y for yes or n for no."); }
i am attempting to use std::cin.fail()
to test rather the input that is stored in the variable char c1
is in fact a char type. Example: if the user inputs a number into c1
then the if statement should execute the throw
statement. however it does not happen. Can anyone assist in making the if statement execute correctly if a user inputs a non char type into the std::cin >> c1
?
Note: i have used this method in a different part of the program to test if an input intostd::cin
is of type int and the if statement works as intended.
Aucun commentaire:
Enregistrer un commentaire