hey :)
i have this piece of code:

while(!(std::cin >> input) || input < 1 || input > 100){
std::cout << "not valid, try again: ";
}

it should allow the user only to be able to write numbers between 1 and 100 (input is a short int), but when the user enters any letters, it displays the error "not valid, try again:" in a loop, so it never stops and you'll have to exit the program.

Please help, anyone

hey :)
i have this piece of code:

while(!(std::cin >> input) || input < 1 || input > 100){
std::cout << "not valid, try again: ";
}

it should allow the user only to be able to write numbers between 1 and 100 (input is a short int), but when the user enters any letters, it displays the error "not valid, try again:" in a loop, so it never stops and you'll have to exit the program.

Please help, anyone

You probably have input defined as an int. It sees a letter and can't handle it, yet doesn't ever throw it away and get past it. So anything you type in after that (if you even ever get prompted again) will fail. You can read the number in as a string instead of an int, then convert it to an integer if it's a legal integer. If it's not a legal integer, throw it away, display your error message, then prompt again. Or read it as an int, then if it is a bad entry, you'll need to throw away the letter (s) using ignore and reset the bad/fail bit in addition to displaying the error message.

http://www.cplusplus.com/reference/iostream/ios/fail.html

cin is expecting a different type than the next word has. You need to clear the stream state first because if it fails you won't be able to read anything else, then you need to remove the bad characters and try again. Removing the bad characters can be tricky, but just killing the whole line is usually fine:

#include <iostream>

int main()
{
  int input;

  while (!(std::cin >> input) || input < 1 || input > 100) {
    std::cout << "not valid, try again: ";

    // Reset the state so we can read again
    std::cin.clear();

    // Remove everything on this line
    std::cin.ignore(1024, '\n');
  }

  std::cout << input << '\n';
}
This article has been dead for over six months. Start a new discussion instead.