Do While Loop menu in C++ [closed] - c++

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
I'm having trouble with this do-while loop menu for a program I'm working on for school. I've checked, and as far as I'm concerned I have written the code correctly. However, when testing, if I type 'y' or 'n' the result is the same: the menu streaming down 100's of times non stop until I exit the program. Any idea on what I'm doing wrong and how I can get it to display the menu properly every time? Thanks in advance.
#include <iostream>
#include <iomanip>
#include <string>
#include "CashRegister.h"
#include "InventoryItem.h"
using namespace std;
int main()
{
// Variables
int selection, numUnits, cont;
double price;
// Use the first constructor for the first item
InventoryItem item1;
item1.setCost(5.0);
item1.setDescription("Adjustable Wrench");
item1.setUnits(10);
// Use the second constructor for the second item
InventoryItem item2("Screwdriver");
item2.setCost(3.0);
item2.setUnits(20);
// Use the third constructor for the remaining items
InventoryItem item3("Pliers", 7.0, 35);
InventoryItem item4("Ratchet", 10.0, 10);
InventoryItem item5("Socket Wrench", 15.0, 7);
do
{
cout << "#\t" << "Item\t\t\t" << "qty on Hand" << endl;
cout << "------------------------------------------------------------------" << endl;
cout << "1\t" << item1.getDescription() << "\t" << setw(3) << item1.getUnits() << endl;
cout << "2\t" << item2.getDescription() << "\t\t" << setw(3) << item2.getUnits() << endl;
cout << "3\t" << item3.getDescription() << "\t\t\t" << setw(3) << item3.getUnits() << endl;
cout << "4\t" << item4.getDescription() << "\t\t\t" << setw(3) << item4.getUnits() << endl;
cout << "5\t" << item5.getDescription() << "\t\t" << setw(3) << item5.getUnits() << endl;
cout << "Which item above is being purchased? ";
cin >> selection;
// Validate the selection
while (selection < 1 || selection > 5)
{
cout << "Error, please make a valid item selection: ";
cin >> selection;
}
cout << "How many units? ";
cin >> numUnits;
// Validate the quantity of units to make sure it isn't a negative value
while (numUnits < 0)
{
cout << "Error, please enter a valid quantity: ";
cin >> numUnits;
}
// Use a switch statement to figure out which cost to pull
switch (selection)
{
case 1: {price = item1.getCost();
item1.changeUnits(numUnits); }
break;
case 2: {price = item2.getCost();
item2.changeUnits(numUnits); }
break;
case 3: {price = item3.getCost();
item3.changeUnits(numUnits); }
break;
case 4: {price = item4.getCost();
item4.changeUnits(numUnits); }
break;
case 5: {price = item5.getCost();
item5.changeUnits(numUnits); }
break;
}
// Create a CashRegister object for this particular selection
CashRegister transaction(price, numUnits);
// Display the totals
cout << fixed << showpoint << setprecision(2);
cout << "Subtotal: $" << transaction.getSubtotal() << endl;
cout << "Sales Tax: $" << transaction.getSalesTax() << endl;
cout << "Total: $" << transaction.getPurchaseTotal() << endl;
// Find out if the user wants to purchase another item
cout << "Do you want to purchase another item? Enter y/n: ";
cin >> cont;
} while (cont != 'n' && cont != 'N');
system("pause");
return 0;
}

Your loop will never break unless you explicitly enter 110 which is the 'n' char in ASCII Codes or 78 which is the 'N'. So change your cont declaration from int cont; to char cont; and then you won't get the infinite loop anymore, and its condition will be valid to possibly break by then unless you have another hidden logical error which will require you to debug it.

Related

cin input not being accepted in while loop [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 11 months ago.
Improve this question
Hi I'm trying to use a cin input but on my second while loop, the inputs are not running though correctly. How would I go about this?
Here's what I have:
#include <iostream>
#include <string>
#include <fstream>
#include <iomanip>
using std::endl;
using std::cout;
using std::cin;
using namespace std;
int a, A;
int main() {
int choice, num;
cout << "State Search" << endl;
cout << "" << endl;
cout << "1. Enter the first letter of your desired state" << endl;
cout << "2. Press 2 to Quit" << endl;
cout << "" << endl;
bool done = false;
while(!done) {
//user inputs desired choice
cin >> choice;
if(choice == a || choice == A)
{
cout << "Which State? (enter a number)" << endl;
cout << "1. Alabama" << endl;
cout << "2. Alaska" << endl;
cout << "3. Arizona" << endl;
cout << "" << endl;
while (!(cin >> num))
{
if(num == 1)
{
cout << "test output 1" << endl;
}
else if (num == 2)
{
cout << "test output 2" << endl;
}
else if (num == 3)
{
cout << "test output 3" << endl;
}
} break;
} break;
}
return 0;
}
Once the user chooses one of the above states using a number I want to display the chosen output.
Here is a cleaned up version of what you are trying to do with some inline comment where you were going wrong.
// You only need to include iostream in your example program
// Only include what you need
#include <iostream>
#include <limits>
// You do not need to include all of the std namespace in the local scope
// if you are using the things you want.
using std::endl;
using std::cout;
using std::cin;
using std::streamsize;
int main()
{
cout << "State Search\n\n";
cout << "1. Enter the first letter of your desired state\n";
cout << "2. Press 2 to Quit\n" << endl;
// Removed all the while(!done) / break; as it is just noise in the current iteration of your program.
// if you use an int for the choice variable, you will actually try to parse the input
// as an integer and return 0 if the user inputs 'a'
// you need to use a char for what you want to do
char choice;
cin >> choice;
// Also your a and A int value do not make sense as they are init to 0
// (global initialization), I guess what you want to do is compare to the char 'a' or 'A'. You could also transform the input to lowercase and compare only to 'a'.
if (choice == 'a' || choice == 'A')
{
// Use \n not std::endl as it will flush the output buffer
// all the time. std::endl is a false friend, use it only
// when you want to present your text to the user.
cout << "Which State? (enter a number)\n";
cout << "1. Alabama\n";
cout << "2. Alaska\n";
cout << "3. Arizona\n" << endl;
// We want to wait until we get a correct input and _then_
// do something with our input.
int num;
while (!(cin >> num))
{
// You might want to say something to your user if he doesn't input a correct number here.
// This will succeed if the user inputs 4, so you might also want to handle that case differently and ask the user to retry too in that case.
// The stream is now in error, you need to reset the state of the stream by clearing the error and emptying the buffer.
cin.clear();
cin.ignore(std::numeric_limits<streamsize>::max(), '\n');
}
// Just showing another way of doing the if / else if dance in C/C++.
switch(num)
{
case 1: cout << "You chose Alabama" << endl; break;
case 2: cout << "You chose Alaska" << endl; break;
case 3: cout << "You chose Arizona" << endl; break;
default: cout << "I do not recognize the State" << endl; break;
}
}
// if we didn't receive 'a' or 'A' we just quit the program.
return 0;
}

function for validation input c++ simple [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
to some this might seem simple, but to me I can't really seem to figure out why this isn't working. I know I could just copy and paste every time inside the while loop to get the result I want, but I've been told that if you have to repeat something more than one time to write a function! My code will double print the number and even though someone would type 8 it will still go into the while loop. Hoping someone can explain why this is happening to me.
int main()
{
int option = selectionHelper();
cout << selectionHelper() << endl;
cout << endl;
if(option == 8)
{
cout << "Exiting program..." << endl;
cout << endl;
cin >> option;
}
while (option != 8)
{
if (option == 1){
cout << selectionHelper() << endl;
cout << endl;
cin >> option;
}else if(option == 2){
cout << selectionHelper() << endl;
cout << endl;
cin >> option;
}else if(option == 3){
cout << selectionHelper() << endl;
cout << endl;
cin >> option;
}else if(option == 4){
cout << selectionHelper() << endl;
cout << endl;
cin >> option;
}else if(option == 5){
cout << selectionHelper() << endl;
cout << endl;
cin >> option;
}else if(option == 6){
cout << selectionHelper() << endl;
cout << endl;
cin >> option;
}else if(option == 7){
cout << selectionHelper() << endl;
cout << endl;
cin >> option;
}else{
cout << "Invalid input... Please try again..." << endl;
cout << endl;
cout << selectionHelper() << endl;
cout << endl;
cin >> option;
}//end else if statement
}//end while loop
}//end function main
and now for my function:
int selectionHelper()
{
int option;
cout << "1. Initialize seating for new performance." << endl;
cout << "2. View seating chart." << endl;
cout << "3. Reserve seats." << endl;
cout << "4. Calculate tickets remaining in row." << endl;
cout << "5. Calculate tickets remaining in theater." << endl;
cout << "6. Calculate total tickets sold." << endl;
cout << "7. Calculate ticket sales." << endl;
cout << "8. Exit program." << endl;
cout << "Option: " << endl;
cin >> option;
return option;
}//end selectionHelper
Thank you for looking at my post!
This answer and others will tell you what code to write to fix your problem. If you should encounter similar problems in the future, try walking through your code with a debugger. (Experience helps too.) Regarding code redundancy: first, it's good that you used the selectionHelper() method. That shows you have good instincts. Here's what you can do further:
Look for lines of code that are the same or differ only by a variable.
Consider condensing them in the following ways:
Can you use a for-loop?
Can you put the code in a method (possibly abstracting out a variable?)
Can you use a broader conditional statement? (That's what you have going on here: if a number is 1, 2, 3, 4, 5, 6, or 7, it's also >0 and <7. That's why we have ranges.)
The program keeps going when they enter 8 because you ask them to input a number after they input 8! So your first chunk of code can be simpler:
int option = selectionHelper();
cout << option << endl <<endl; // <-- output option, don't call selectionHelper() here again, that's why you get double printing
if(option == 8)
{
cout << "Exiting program..." << endl;
cout << endl;
//cin >> option; // <-- don't input here again!
}
The key here to simplifying your code is to recognize that you only write different code in a few cases. So, here's your while loop:
while (option != 8)
{
if (option > 0 && option < 8){
cout << selectionHelper() << endl;
cout << endl;
cin >> option;
}else{
cout << "Invalid input... Please try again..." << ends << endl;
cout << selectionHelper() << endl << endl;
cin >> option;
}//end else if statement
}
You must modify your code in the following ways:
int option = selectionHelper();
cout << option << endl;
And also:
if(option == 8)
{
cout << "Exiting program..." << endl;
}
You can simplify your code down to (using partly the simplification made by cuniculus but also fixing the mistake in your own code of wrong using option):
#include <iostream>
using namespace std;
int selectionHelper()
{
int option;
cout << "1. Initialize seating for new performance." << endl;
cout << "2. View seating chart." << endl;
cout << "3. Reserve seats." << endl;
cout << "4. Calculate tickets remaining in row." << endl;
cout << "5. Calculate tickets remaining in theater." << endl;
cout << "6. Calculate total tickets sold." << endl;
cout << "7. Calculate ticket sales." << endl;
cout << "8. Exit program." << endl;
cout << "Option: " << endl;
cin >> option;
return option;
}//end selectionHelper
int main()
{
int option = selectionHelper();
while (option != 8)
{
if (option > 0 && option < 8){
option = selectionHelper();
}else{
cout << "Invalid input... Please try again..." << ends << endl;
option = selectionHelper();
}//end else if statement
}
cout << "Exiting program..." << endl;
return 0;
}//end function main
Your mistake was basically in calling selectionHelper too many times, when only once is needed to set the option variable. You have a similar thing going on in your whole if-else structure - but I'll leave it up to you to fix that if needed, the solution is the same.

Program not saving inputted entries? (C++) [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
I am supposed to make a class AddressBook containing a class called Person. My program almost, works, except when I add a person, it doesn't remember it in the next iteration of the Command menu and Display All turns up "There are 0 people in your address book." What is wrong with my code?
#include <iostream>
#include <string>
using namespace std;
class AddressBook {
public:
class Person
{
public:
char firstName[15];
char lastName[15];
char personID[15];
};
Person entries[100];
unsigned int total;
AddressBook()
{
total = 0;
}
void AddPerson()
{
cout << "This is entry number " << (total + 1) << " in your address book. " << endl;
cout << "What shall we put for the first and last name? Limit both to under 15 characters. Example: Bob Smith" << endl;
cin >> entries[total].firstName >> entries[total].lastName;
cout << "What is " << entries[total].firstName << " " << entries[total].lastName << "'s ID code?" << endl;
cin >> entries[total].personID;
++total;
cout << "..." << endl << "Successfully Added." << endl;
};
void DisplayPerson(int i)
{
cout << "Entry " << i + 1 << ": " << endl;
cout << "FIRST NAME: " << entries[i].firstName << endl;
cout << "LAST NAME: " << entries[i].lastName << endl;
cout << "ID: " << entries[i].personID << endl;
};
void DisplayEveryone()
{
cout << "You have " << total << " People in your address book." << endl;
for (int i = 0; i < total; ++i)
DisplayPerson(i);
};
void SearchPerson()
{
char lastname[32];
cout << "Please enter the last name of the person you wish to find." << endl;
cin >> lastname;
for (int i = 0; i < total; ++i)
{
if (strcmp(lastname, entries[i].lastName) == 0)
{
cout << "Person Found. " << endl;
DisplayPerson(i);
cout << endl;
}
}
};
};
int main() {
char command;
bool Exit = false;
while (Exit == false)
{
AddressBook Address_Book;
cout << "---------------COMMANDS---------------" << endl;
cout << "A: Add Person To Address Book" << endl;
cout << "S: Search for Person in Address Book" << endl;
cout << "D: Display Everyone In Address Book" << endl << endl;
cout << "Type the letter of your command: ";
cin >> command;
cout << endl;
switch (command) {
case 'A':
case 'a':
Address_Book.AddPerson();
break;
case 'S':
case 's':
Address_Book.SearchPerson();
break;
case 'D':
case 'd':
Address_Book.DisplayEveryone();
break;
default:
cout << "That is not a valid command. Closing Address Book." << endl;
cout << endl;
}
}
}
The reason is that you create a new address book in each iteration of the while loop and throw it away at the end of the iteration:
This
AddressBook Address_Book;
creates a new address book that is "thrown away" when you reach the end of its scope (ie. the end of the loop).
In reality, do you buy a new address book whenever you want to make new entry? No. You first buy the book and then (possibly in a while loop) you add entries. Move the above line outside of the loop.
Your problem is in the declaration of your address book.
Change it to the following:
AddressBook Address_Book;
while (Exit == false) {
//Ask for input and respond.
}
In your version Address_Book is declared at the start of the while loop. This means that every time an iteration of the loop completes and execution returns to the start of the block, a new local Address_Book object is created that has no knowledge of the previous objects data.

Alternatives of switch [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
In the below code, I need help with the alternatives of switch case, I mean how can I avoid switch and use the other option to execute the code.
Code:
cout << " *********************Intensive Program 1***********************\n\n" << endl;
cout << "\nHere's the menu of choices: ";
cout << "\n1. Add a Circle.\n";
cout << "2. Print a Circle. \n";
cout << "3. Print all Cricles \n";
cout << "4. Exit.\n";
cout << "\nPlease enter your choice: ";
cin >> choice;
while (choice <4){
switch (choice){
case 1:
// For adding cirles to the class
cout << " Enter the value for the radius of the circle: ";
cin >> radius;
cout << " Enter the value for the center of the circle: ";
cin >> center;
myCircle[thisPosition] = new Circle(radius, center);
myCircle[thisPosition]->PrintCircle();
thisPosition++;
break;
case 2: // For printing a particular cirle from the list of cirles
cout << " Enter the Value for which Circle to Print: ";
cin >> printPosition;
myCircle[printPosition - 1]->PrintCircle();
break;
case 3: // For printing all the circles in the class object array pointer list
cout << "\n";
for (int i = 0; i < thisPosition; i++){
myCircle[i]->PrintCircle();
cout << "\n==============================" << endl;
}
break;
case 4:
cout << "\n Good Bye !!! \n " << endl;
break;
}
cout << "\nHere's the menu of choices: ";
cout << "\n1. Add a Circle.\n";
cout << "2. Print a Circle. \n";
cout << "3. Print all Cricles \n";
cout << "4. Exit.";
cout << "Please enter your choice: ";
cin >> choice;
system("pause");
}
}
You could also use a std::vector<std::function<void()>> choices(5);... and call it like choices[choice](); after you filled it with the alternative choices like choices[1] = &function_1; etc...
But I have a feeling the real question is not really about how to avoid switch...
[EDIT]
Based on your comment, I think the question is how to avoid duplicating the "menu" output. Simply refactor like this using a do..while:
cout << " *********************Intensive Program 1***********************\n\n" << endl;
cout << "\nHere's the menu of choices: ";
cout << "\n1. Add a Circle.\n";
cout << "2. Print a Circle. \n";
cout << "3. Print all Cricles \n";
cout << "4. Exit.\n";
cout << "\nPlease enter your choice: ";
do
{
cin >> choice;
switch (choice){
case 1:
// For adding cirles to the class
cout << " Enter the value for the radius of the circle: ";
cin >> radius;
cout << " Enter the value for the center of the circle: ";
cin >> center;
myCircle[thisPosition] = new Circle(radius, center);
myCircle[thisPosition]->PrintCircle();
thisPosition++;
break;
case 2: // For printing a particular cirle from the list of cirles
cout << " Enter the Value for which Circle to Print: ";
cin >> printPosition;
myCircle[printPosition - 1]->PrintCircle();
break;
case 3: // For printing all the circles in the class object array pointer list
cout << "\n";
for (int i = 0; i < thisPosition; i++){
myCircle[i]->PrintCircle();
cout << "\n==============================" << endl;
}
break;
case 4:
cout << "\n Good Bye !!! \n " << endl;
break;
}
system("pause");
}
} while(choice != 4);
If you still want the menu to be repeated for each choice, then simply cut and paste the menu printing at the start of the do..while loop.
As a side note, I strongly suggest you read https://mikeash.com/getting_answers.html for the next time.
Using if-else ladder is one of the alternatives for switch statements.
cout << " *********************Intensive Program 1***********************\n\n" << endl;
cout << "\nHere's the menu of choices: ";
cout << "\n1. Add a Circle.\n";
cout << "2. Print a Circle. \n";
cout << "3. Print all Cricles \n";
cout << "4. Exit.\n";
cout << "\nPlease enter your choice: ";
cin >> choice;
while (choice <4){
if(choice==1)
{
// For adding cirles to the class
cout << " Enter the value for the radius of the circle: ";
cin >> radius;
cout << " Enter the value for the center of the circle: ";
cin >> center;
myCircle[thisPosition] = new Circle(radius, center);
myCircle[thisPosition]->PrintCircle();
thisPosition++;
}
else if(choice==2)
{ // For printing a particular cirle from the list of cirles
cout << " Enter the Value for which Circle to Print: ";
cin >> printPosition;
myCircle[printPosition - 1]->PrintCircle();
}
else if(choice==3) // For printing all the circles in the class object array pointer list
{
cout << "\n";
for (int i = 0; i < thisPosition; i++){
myCircle[i]->PrintCircle();
cout << "\n==============================" << endl;
}
}
else
{
cout << "\n Good Bye !!! \n " << endl;
}
}
system("pause");
}

C++ error with input validation in a do-while loop

I'm creating a very simple number guessing game for a school project and am having trouble with the repeating main menu. I created it using a do-while loop and the problem I'm having is that the menu selection variable is an int, and so when I (or the user) enters a non-int input by accident when selecting from the menu the }while(condition) at the end of the main loop can't catch it and the program repeats infinitely. Conversely if you enter an invalid int at menu selection the program catches it displays the "invalid input" message and then repeats the main menu.
It's kind of hard to explain in writing exactly what I mean so here is the source code with relevant lines denoted with an asterisk. I'm saving as .cpp and am compiling in linux using g++ -ansi -pedantic -Wall -Werror The teacher has forbidden hardcoding in conditional statements hence the global constants.
#include <iostream>
#include <ctime>
#include <cstdlib>
using namespace std;
const int PLAY = 1, HIGH_SCORE = 2, EXIT = 3;
const char YES = 'y', NO = 'n';
int main()
{
// Randomly generated value
int randomNumber;
// User input
int userGuess, menuChoice;
char repeat;
// Calculated value
int numberOfGuesses;
// Place-holder values (to be replaced by calculated values)
int score1 = 1000, score2 = 2000, score3 = 3000;
cout << endl << endl;
cout << "Greetings! This is a number guessing game where I think of" << endl
<< "a whole number between one and ten and you try to guess it!" << endl
<< "You can guess as many times as you like, so don't be afraid" << endl
<< "to use trial and error, but your score is based on the " << endl
<< "number of guesses you make (the lower the better) so don't " << endl
<< "guess too haphazardly. Remember, only guess whole numbers!" << endl
<< endl;
do
{
cout << endl << "Main menu." << endl
<< "1. Play game" << endl
<< "2. Display high scores" << endl
<< "3. Exit game" << endl
<< "Please select an option: ";
cin >> menuChoice;
if (cin.fail()){
cout << "Please enter a valid choice" << endl;
continue;
}
cin.ignore();
switch(menuChoice)
{
case PLAY:
do
{
unsigned seed = time(0);
srand(seed);
randomNumber = 1 + rand() % 10;
cout << endl << "Press enter when you're ready to begin!";
cin.ignore();
cout << "Ok I thought of one!" << endl << endl;
numberOfGuesses = 0;
do
{
numberOfGuesses++;
cout << "Enter your guess: ";
cin >> userGuess;
cin.ignore();
// Check user's guess
if (userGuess == randomNumber)
cout << "Correct! That was impressive!" << endl << endl;
else if (userGuess < randomNumber)
cout << "Not quite, you guessed low." << endl << endl;
else if (userGuess > randomNumber)
cout << "Not quite, you guessed high." << endl << endl;
}while (userGuess != randomNumber);
cout << "Your score for this game was " << numberOfGuesses << endl;
// Determine if a high score was beaten
if (numberOfGuesses <= score1)
{
score3 = score2;
score2 = score1;
score1 = numberOfGuesses;
cout << "That's a new all time high score!" << endl;
}
else if (numberOfGuesses <= score2)
{
score3 = score2;
score2 = numberOfGuesses;
cout << "That's a new high score!" << endl;
}
else if (numberOfGuesses <= score3)
{
score3 = numberOfGuesses;
cout << "That's a new high score!" << endl;
}
else
{
cout << endl;
}
cout << "Would you like to play again? y/n: ";
cin.get(repeat);
cin.ignore();
while (tolower(repeat) != YES && tolower(repeat) != NO)
{
cout << endl;
cout << "Sorry, that is an invalid choice." << endl
<< "Please enter 'y' for yes or 'n' for no: ";
cin.get(repeat);
cin.ignore();
}
}while (tolower(repeat) == YES);
break;
case HIGH_SCORE:
cout << endl << "High Score 1: " << score1 << endl
<< "High Score 2: " << score2 << endl
<< "High Score 3: " << score3 << endl << endl;
cout << "Press enter to continue. ";
cin.ignore();
break;
case EXIT:
cout << endl << "Thanks for playing, I'll see you next time!" << endl << endl;
break;
default:
cout << endl << "That is an invalid selection, please enter '1', '2' or '3'"
<< endl;
break;
}
}while (menuChoice != EXIT);
return 0;
}
Code Edited in regards to current answer.
Please let me know if you need anymore information, thanks in advanced!
Use cin.fail() like this (instead of just cin >> menuChoice;) (modelled after this post):
cin >> menuChoice;
if (cin.fail()) {
cout << "Please enter a valid choice" << endl;
cin.clear();
cin.ignore();
continue;
}
//Remove the cin.ignore() at this place!
For more detailed info, see this SO thread
Use a do-while to ensure that the loop body will run at least once.
By using a do-while and prompting a user outside the loop you assume the user wants to play the game once which may not be the case.
A cleaner approach IMO would be use a while loop. Display the menu outside the loop and at the end of the loop. The user will have the choice to exit immediately.
cout << "Greetings.....
cout << menu
// Get menuChoice input here.
while(menuChoice != EXIT){
...
cout << menu //reprompt at end to continue or exit cleanly
// Get menuChoice input here
}
Input Validation is a perfect time to use a do-while
do{
if(!cin){
cout << "Invalid input"
cin.clear()
cin.ignore(numeric_limits<streamsize>::max(), '\n');
}
}while(!(cin >> menuChoice)) // This gets console input. If fail, loop.
Use numeric_limits<streamsize>::max() to completely clear the
buffer.
Use cin.clear() to reset the fail flag on cin so it wont
always be false.
cin.fail() is fine. However some would consider !cin more natural.