i saw an unusual problem in this code:
#include <iostream>
using namespace std;
int main()
{
int number;
bool repeat=true;
while (repeat)
{
cout<<"\nEnter a number:";
cin>>number;
cout<<"\nNumber is:"
<<number;
cout<<"\nRepeat?:";
cin>>repeat;
}
system("pause");
return 0;
}
here in this code when i put a character such “A” in int type variable while loop repeats over and over and don’t ask me whether to repeat or not.
this problem just appear when i put characters not integers.
this appears with for too.
why should happen this?
thanks
After reading in user input which cannot be converted, the input stream is in an invalid state. You need to empty the stream and call the
clearmethod to reset the error bits on the stream in order to resume normal operation.If you detect that input was not successful (using the input streams state bits, accessible via methods like
good()orfail()etc.) you can reset the stream using code similar to this: