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:
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.