here is my simple code. I ask the user for a non-negative number, if it's not a number then I print on screen something like "not a number".
If the user writes a word, or a word followed by a number, the program correctly exits. BUT if he writes a number followed by a word (or a letter), then the "cin.fail()" does not fail! Why???
Can anybody help me on this?
Lallina
int main () {
double n;
bool question = false;
char answer;
int factorial;
while (question == false) {
cout << "... Choose a non-negative integer" << endl;
cin >> n;
//In case the user does not enter a number...
if (cin.fail()) {
cout << "Hey, that was not a number!" << " Exiting program..." << endl;
cin.clear
return 0;
}
else{
cout << "The number you have chosen is " << n << endl;
cout << "Happy with that? (Answer y/n)" << endl;
cin >> answer;
if (answer == 'y') question = true; //it then exits the while loop
}
}
}