cin.fail() does not work properly

Hi everybody,

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
}
}
}

Last edited on
It is working just fine. It just doesn't require any space to be between the integer and something else.

Here is a post that deals with this very issue.
http://www.cplusplus.com/forum/beginner/13044/

In my answer, I had too much fun wrapping it all up in a class. You don't need to do that. Just pay attention to how lines 29 through 41 work.

You also don't need to use getline(). You can also use the cin >> mystring trick to get a string ending at whitespace in the input.

Hope this helps.
Topic archived. No new replies allowed.