loop until correct added

If I type a char in int datatype input then the loop becomes infinite. I tried to handle it but can't. However, my program is:
#include<iostream>
using namespace std;
int main()
{
int number=0;

while(1)
{
cout<<"Enter the number: ";
cin>>number;

if( ! (cin>>number) )
{
cout<<"Entry not correct!";

}
else
{
cout<<"You entered number: "<<number<<endl;
break;
}
}
}
When you input characters, cin>>number tries to read it. However it knows that it is reading a number, which consist of digits.
When it sees a characters, it says: "wait, it is not a digit. Something went wrong here. Lets mark stream as failed and leave that strange input here. Let user look at it and decide what to do, maybe it was supposed to be read by someone else."

You do not handle this stuff, so when your loop starts again, it tries to read same character and fails in the same way. And again.

So that is why you have infinite loop here (actually you have it in the first place because you asked for it)
Topic archived. No new replies allowed.