So I'm displaying a menu using a do while loop as shown below, and I want the user to be prompted with the menu until they make a valid selection- by entering the digits 1, 2, 3 or 4. I then want to use a switch case statement for identifying the users choice and executing the relevant block of code. When it comes to input validation though, how can I account for the user entering a letter instead of a numerical digit? The below code successfully continues to the next iteration to reprompt the user when they enter a letter, except that it enters a continuous loop.
int selection;
do{
cout << "Which option would you like to select? (select 1, 2, or 3)";
cout << "1: Option 1" << endl;
cout << "2: Option 2" << endl;
cout << "3: Option 2" << endl;
if(!(cin >> selection)){
cout << "Please select an integer from 1-4." << endl;
cin.clear()
}
}while(selection != (1) or (2) or (3) or (4));
I've tried inserting the code below using istringstream to stream the users response from a string into an int inside the while loop as an alternative method to try solving the problem but to no avail.
string temp;
cin >> temp;
clearInputBuffer();
istringstream is(temp);
is >> selection;
UPDATED CODE - still getting an infinite loop (only when the user enters an alphabetic
character; integers behaveas expected)
int selection;
do{
cout << "Which option would you like to select? (select 1, 2, or 3)";
cout << "1: Option 1" << endl;
cout << "2: Option 2" << endl;
cout << "3: Option 2" << endl;
if(std::cin >> selection){
cout << "Enter the new price: ";
}
else if(!std::cin.eof()){
cout << "Please select an integer from 1-4." << endl;
cin.clear();
}
}while(selection != 1 && selection != 2 && selection != 3 && selection != 4);