Reputation: 3796
I know that there are many questions like this, with correct answers. However, what I am concerned here is why my explanation of the below code is wrong.
#include <iostream>
#include <string>
int main(){
std::cout << "Write an integer:\n>";
int n;
std::cin >> n;
while (!std::cin) {
std::cout << "ERROR, you are allowed to enter an integer only.Try again!\n>";
std::cin.clear();
//std::cin.ignore(10000,'\n');
std::cin >> n;
}
std::cout << "\nYou entered the integer: " << n;
return 0;
}
What happens now is that if I enter a character like 'h', it will continue showing the Error sentence forever.
Let's assume that I did not run the program. I would explain the above code as below:
When I enter an invalid input such as 'h', cin will fail and the while condition will become true. In addition, there will be a '\n' character in the input buffer.
Now the program will display the error message and clear the cin error flag. Now cin returns to original state, able to get input again.
Now there is a newline character in the input buffer and cin will skip it, allowing the user to enter another character again. So the program should work fine(However, in reality it does not!)
Why is it not working as I have explained above?
Upvotes: 2
Views: 1008
Reputation: 153909
If you uncomment the std::cin.ignore
, the code should work. Without the ignore
, the 'h'
is not removed from the sequence, so you attempt to read it again and again.
Upvotes: 2
Reputation: 758
Well, characters in C (and C++ i guess) are actually small integer numbers so if you want to check whether input is digit (or contains digit) you should check it for instance with function from types.h (IIRC). I'am not sure if there isn't any better, more C++'ish method.
Also what you basically do here is checking whether std:cin is not true. Are you sure that empty stream, or stream containing only newline character is false ?
Upvotes: 0