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++
Be careful with this. The following will produce an infinite loop if the user enters a letter:
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 callsstd::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:
You'll probably want to use something safer than
atoi
though.