Reputation: 7583
I have a little program, and I want to evaluate input. The input for the N variable should only be a number between 1 and 2000. Now, the below code that I wrote works fine if I put in correct/incorrect numbers, but when I put in some random letters (I have to make sure that there's only numbers, so I have to handle if someone puts in letters), the prompt gets written out as many times as much letters I've put in, and I only want it to be put out once. So if I write 34, it works. If I write 3355453, the input gets checked and the user gets prompted to try again with a number between 1 and 2000. When I write a letter 'x', the the input gets checked and the user gets prompted to try again with a number between 1 and 2000 again, but if I write more letters, for example xxxx - the prompt appears 4 times instead of one. If i put in 7 letters, the propt appears 7 times. Any way to solve this? Thank you!
do {
cout << "Please put in a number between 1 and 2000." << endl;
cin >> N;
if(cin.fail() || N<1 || N>2000){
cin.clear();
cin.ignore();
}
} while(cin.fail() || N<1 || N>2000);
Upvotes: 2
Views: 239