I have a menu created where the user has to input a number between 1-5, anytime the user inputs a numeric value it works perfect, it will either go to the specified case or in case of an invalid digit, it will go to default and an error message will appear.
Now my problem is when the user inputs an alphabet letter, the program keeps looping and looping, it won't stop, each time going through the default.
I've tried many things! Using an if statement to check whether the number is 1 <= value <= 5, doesn't work. I tried hard-coding in a number if the input is not between those values, it still loops forever. I tried doing cim.good(), not sure if I did it right, but the way I did it doesn't work. I also tried to use the isdigit() function, but same problem, it doesn't work... I really don't know what I gotta do. Here is what I have (simplified).
int menu()
{
int key;
cout << endl << "--------- Main Menu ----------" << endl;
cout << "1: Sort" << endl << "2: Add" << endl;
cout << "3: Search" << endl << "4: History" << endl << "5: Exit" << endl;
cout << "Please pick one: ";
cin >> key;
return(key);
}`
void main()
{
Menu:
key = menu();
switch(key)
{
case 1:
goto Menu;
case 2:
goto Menu;
case 3:
goto Menu;
case 4:
goto Menu;
case 5:
break;
default:
cout << endl << "Invalid entry, please try again" << endl;
goto Menu;
}
}
I deleted what's inside the cases to make it look nicer. When I type in a key, I keep getting the "Invalid entry, please try again" message, so that's where it is going through.
EDIT: Well I apologize for the 'goto', didn't know it was frown upon, still learning! Thank you everyone for all the help though. I will start removing them for sure.