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 as开发者_如何转开发k 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 clear
method 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()
or fail()
etc.) you can reset the stream using code similar to this:
std::cin.clear();
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
You put cin in an error state when you failed to extract an int from it, and didn't recover. So when you then tried to extract repeat from it, the stream is still in a failed state. You need to check for the failure of number (just use if(cin >> number)).
精彩评论