1

I have a program in which the user must make a selection by entering a number 1-5. How would I handle any errors that might arise from them entering in a digit outside of those bounds or even a character?

Edit: Sorry I forgot to mention this would be in C++

reformed
  • 4,505
  • 11
  • 62
  • 88
Joshua
  • 79
  • 1
  • 8

1 Answers1

2

Be careful with this. The following will produce an infinite loop if the user enters a letter:

int main(int argc, char* argv[])
{
  int i=0;
  do {
    std::cout << "Input a number, 1-5: ";
    std::cin >> i;
  } while (i <1 || i > 5);
  return 0;
}

The issue is that std::cin >> i will not remove anything from the input stream, unless it's a number. So when it loops around and calls std::cin>>i a second time, it reads the same thing as before, and never gives the user a chance to enter anything useful.

So the safer bet is to read a string first, and then check for numeric input:

int main(int argc, char* argv[])
{
  int i=0;
  std::string s;
  do {
    std::cout << "Input a number, 1-5: ";
    std::cin >> s;
    i = atoi(s.c_str());
  } while (i <1 || i > 5);
  return 0;
}

You'll probably want to use something safer than atoi though.

Tim
  • 8,912
  • 3
  • 39
  • 57
  • This will do it... Thanks... I'll delete my answer. – Pepe Feb 12 '11 at 02:16
  • How about wrapping that atoi in a try/catch? – Steven Sudit Feb 12 '11 at 03:22
  • @SteveSudit: `atoi()` cannot (should not) throw exceptions since it is a C runtime function. Assuming that this is `std::atoi()` anyway. `atoi` does not do anything useful in the case of a non-numeric string. Use something like `strtoul` instead. – D.Shawley Feb 28 '11 at 03:47
  • 1
    You should check if the extraction operator fails as well. Enter EOF (Ctrl+D on UN*X, Ctrl+Z on Windows) once if you want to see an infinite loop. – D.Shawley Feb 28 '11 at 03:51