I have a simple c++ program that has a menu and allows the user to select an option with a number. There is also a block of code that ensures the input from the user is valid, however, when I for example input a letter ("s"). Instead of showing an error message and then allowing the user to input a valid response, I receive an infinite loop of the same error message. Code:
#include <iostream>
#include <algorithm>
using namespace std;
int main(){
const string PROMPT = ">> ";
int options[3] = {1, 2, 3};
int option;
// Display menu
cout << "MENU" << endl
<< "1\tAdult Tickets" << endl
<<"2\tStudent Tickets" << endl
<< "3\t2 Adults, 2 Children Tickets" << endl << endl;
// Getting option from the user and validating it
do {
// Prompt for input and get option from user
cin >> option;
// Displaying appropriate error messages
if (!isdigit(option)){
// Invalid data type
cout << "This is not a valid number!" << endl;
// Not on the options menu
} else if (!(find(options, options + sizeof(options)/ sizeof(options[0]), option))){
cout << "This option is not on the menu!" << endl;
}
} while (!isdigit(option) || !(find(options, options + sizeof(options)/ sizeof(options[0]), option)));
return 0;
}
This is an example of the output when I input "s"
This is not a valid number This is not a valid number! This is not a valid number! This is not a valid number! This is not a valid number! This is not a valid number! This is not a valid number!...
Any help will be highly appreciated and thank you in advance.