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?