lte__
lte__

Reputation: 7583

cin.fail error handling issues

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

Answers (1)

Shmil The Cat
Shmil The Cat

Reputation: 4668

Replace cin.ignore() w/ cin.ignore(INT_MAX, '\n');

Upvotes: 2

Related Questions