I am trying to get a program to display a menu with options, then given the user input, display a certain message. After it displays their message I want the loop to go back to displaying the message until they choose the quit option. How do I get the loop to return to displaying the menu after any choice of 1-3?
#include <iostream>
#include <iomanip>
using namespace std;
int main(){
int menu_choice;
cout << "Select a numerical option:" << endl << "=== menu ===" << endl << "1. Fox" << endl << "2. Bunny" << endl << "3. Sloth" << endl << "4. Quit" << endl;
cin >> menu_choice;
while (menu_choice >= 1 && menu_choice <= 4)
{
while (menu_choice == 1)
{
cout << "1 work" << endl;
menu_choice = 0;
continue;
}
while (menu_choice == 2)
{
cout << "2 work" << endl;
menu_choice = 0;
continue;
}
while (menu_choice == 3)
{
cout << "3 work" << endl;
menu_choice = 0;
continue;
}
while (menu_choice == 4)
{
cout << "4 work" << endl;
menu_choice = 0;
continue;
}
}
return 0;
}
Your code is displaying the menu only 1 time. If the user enters an invalid choice, you exit right away. If the user enters a valid choice, you do the chosen work, but then you exit rather than display the menu again. All of your while..continue loops are completely useless, they only run 1 time at most, setting the menu_choice to 0, which breaks your outer while loop so it runs only 1 time as well.
You need an outer loop that runs continuously, displaying the menu each time, until you are actually ready to exit.
You should also replace the useless while..continue loops with if/else blocks, or better a single switch block.
Try something more like this instead:
#include <iostream>
#include <limits>
using namespace std;
int main()
{
int menu_choice;
do
{
cout << "Select a numerical option:" << endl
<< "=== menu ===" << endl
<< "1. Fox" << endl
<< "2. Bunny" << endl
<< "3. Sloth" << endl
<< "4. Quit" << endl;
if (!(cin >> menu_choice))
{
menu_choice = 0;
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
}
switch (menu_choice)
{
case 1:
cout << "1 work" << endl;
break;
case 2:
cout << "2 work" << endl;
break;
case 3:
cout << "3 work" << endl;
break;
case 4:
cout << "4 work" << endl;
break;
default:
cout << "Bad choice! Try again" << endl;
break;
}
}
while (menu_choice != 4);
return 0;
}
#Remy Lebeau was quicker posting and his answer is well written, but since I was done writing the code and you might benefit looking at different implementations I'm posting the code. I deliberately chose not to use switch since you might not have seen it before.
#include <iomanip>
#include <iostream>
using namespace std;
int main() {
bool quit = false;
int menu_choice;
while(!quit) {
cout << "Select a numerical option:" << endl
<< "=== menu ===" << endl
<< "1. Fox" << endl
<< "2. Bunny" << endl
<< "3. Sloth" << endl
<< "4. Quit" << endl;
if(cin >> menu_choice) {
if(menu_choice == 1) {
cout << "1 work" << endl;
}
if(menu_choice == 2) {
cout << "2 work" << endl;
}
if(menu_choice == 3) {
cout << "3 work" << endl;
}
if(menu_choice == 4) {
cout << "Bye" << endl;
quit = true; // Set quit to true to stop the while loop
} else {
cout << "Invalid number" << endl;
}
} else {
cout << "Bad input" << endl;
cin.clear();
cin.ignore();
}
}
return 0;
}
Note that the cin.ignore and cin.clear are important and often confuse people new to this. Read this question for the details.
Related
I'm struggling to get my switch statement to go back to the start after an option is selected, to allow the user to input another option. I removed all the code from the switch cases just to cut it down a bit.
Thanks
int main() {
char tab = '\t';
int input;
bool menu = true;
FlightSystem f;
vector <Aircraft> allAircraftList_{};
std::string flightNumber, airline, aircraftType, gridReference;
int groundSpeed, altitude, heading;
const int MaxAlt = 60000, MinAlt = 0, MaxSpeed = 800, MinHeading = 0, MaxHeading = 360;
regex fNumber{ "([a-z]{2}([a-z])?[0-9]([0-9])?([0-9])?([0-9])?([0-9])?)" };
do {
std::cout << "#########################################################" << endl;
std::cout << "#Flight Control Simulation#" << endl;
std::cout << "#########################################################" << endl;
std::cout << "" << endl;
std::cout << tab << "1. Add Aircraft" << endl;
std::cout << tab << "2. List All Aircraft" << endl;
std::cout << tab << "3. List All Cruising Aircraft" << endl;
std::cout << tab << "4. Number of Aircrafts in Sector" << endl;
std::cout << tab << "5. Remove Aircraft" << endl;
std::cout << tab << "6. Change Heading" << endl;
std::cout << tab << "7. Get Heading" << endl;
std::cout << tab << "8. Change Altitude" << endl;
std::cout << tab << "9. Get Altitude" << endl;
std::cout << "" << endl;
std::cout << "---------------------------------------------------------" << endl;
std::cout << "Please enter an option, between 1-9:" << endl;
std::cin >> input;
switch (input) {
case:
break;
default:
cout << "Your selection must be between 1 and 9" << endl;
}
return 0;
} while (input != 9);
}
Here is my advice. Use a while loop. do-while loop in this case is unnecessary.
here's how it can be used (i made a simple program that enters a number, you can modify it accordingly, just replace my code with your switch statements)
#include<iostream>
using namespace std;
int main()
{
int x;
bool repeat = true;
while(repeat)
{
cout<<"enter a number"<<endl;
cin>>x;
cout<<"do you want to enter another number (y/n)"<<endl;
char ch;
cin>>ch;
if(ch=='y'||ch =='Y')
continue;
else
repeat = false;
}
cout<<"you entered "<<x;
}
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
All of my commands and alters to the array work individually. However, when i try to return to the menu the screen just starts jittering and will not continue. I am forced to close the program. How do i fix this.
/* Programmer: Joshua Zuber
Program Desc: This Program will allow the user to select an icon to display around an array message!
Program Name: Array Demonstration
Clean Compile Date:
*/
#include<iostream>
#include<string>
#include<iomanip>
#include<cstdlib>
#include<ctime>
using namespace std;
int main()
{
// Arrays
string Masterfile[] = "I want to thank all the C++ students who has helped me this semester. You have inspired me to work harder and to be able to design small C++ programs using a gamming approach. ";
string Studentfile[]= "";
// Variables
int Icon;
char again = 'y';
int i;
int j;
int menu = 'y';
int menu2 = 'n';
int menu3 = 'n';
int menu4 = 'n';
int menu5 = 'n';
int objEdit;
while (toupper(again) == 'Y') // Start Main Loop
{
cout << "Welcome to Array Demonstration!" << "\n\n";
cout << Masterfile[0] << "\n\n";
while(toupper(menu) == 'Y' || toupper(menu2) == 'Y' || toupper(menu3) == 'Y' || toupper(menu4) == 'Y' || toupper(menu5) == 'Y' ) // Start Array Menu Loop
{
cout << "Please select one of the below options to edit this string!" << "\n\n";
Studentfile[0] = Masterfile[0];
cout << "1. Size" << "\n\n";
cout << "2. Replace {all of the C++ students} with {My instructer, Professor Penn}" << "\n\n";
cout << "3. Swap the word {small} with {efficient}" << "\n\n";
cout << "4. Erase the phrase {using a gamming approach}" << "\n\n";
cout << "5. View Final Product" << "\n\n";
cin >> objEdit;
if(objEdit == 1) // Menu Array Size Check
{
cout << "The size of the original string is: " << Masterfile[0].size() << "\n\n";
cout << "\n\n" << "Would you like to return to menu? Y/N " << "\n\n";
cin >> menu2 ;
system("cls");
}
else if(objEdit == 2) // Menu 2nd Option
{
cout << "Changing the phrases!" << "\n\n";
Studentfile[0].replace(16,20,"My instructer, Professor Penn");
cout << Studentfile[0] << "\n\n";
cout << "\n\n" << "Would you like to return to menu? Y/N " << "\n\n";
cin >> menu3;
system("cls");
}
else if(objEdit == 3) // Menu 3rd Option
{
cout << "Changing the phrases!" << "\n\n";
Studentfile[0].replace(131,5,"efficient" );
cout << Studentfile[0] << "\n\n";
cout << "\n\n" << "Would you like to return to menu? Y/N " << "\n\n";
cin >> menu4;
system("cls");
}
else if(objEdit == 4) // Menu 3rd Option
{
cout << "Changing the phrases!" << "\n\n";
Studentfile[0].erase(150);
cout << Studentfile[0] << "\n\n";
cout << "\n\n" << "Would you like to return to menu? Y/N " << "\n\n";
cin >> menu5;
system("cls");
}
else if (objEdit <=0 || objEdit >=6) // Menu Failsafe
{
cout << "Please Select a Valid Number" << "\n\n";
cout << "1. Size" << "\n\n";
cout << "2. Replace {all of the C++ students} with {My instructer, Professor Penn}" << "\n\n";
cout << "3. Swap the word {small} with {efficient}" << "\n\n";
cout << "4. Erase the phrase {using a gamming approach}" << "\n\n";
cout << "5. View Final Product" << "\n\n";
cin >> objEdit;
}
else if(objEdit == 5 || toupper(menu) == 'N') // Menu 5th Option
{
cout << "Please Select one of the following numbers to choose a symbol!" << "\n\n";
cout << "1. *" << "\n\n";
cout << "2. ^" << "\n\n";
cout << "3. #" << "\n\n";
cout << "4. +" << "\n\n";
cin >> Icon;
system("cls");
if(Icon <= 0, Icon >= 5) // User Failsafe
{
cout << "You're Entry Is Not Valid" << "\n\n";
cout << "Please Select one of the following numbers to choose a symbol!" << "\n\n";
cout << "1. *" << "\n\n";
cout << "2. ^" << "\n\n";
cout << "3. #" << "\n\n";
cout << "4. +" << "\n\n";
cin >> Icon;
system("cls");
}
else // Icon Breakdown
{
if(Icon == 1) // Icon Choice 1
{
for (i=1;i<=1;i++)
{
for (j=1;j<=i;j++);
{
cout << "*******************************************************************************" << "\n";
cout << Studentfile[0] << "\n";
cout << "*******************************************************************************" << "\n";
cout << endl;
cout << "\n\n" << "Do you wish to play again? Y/N " << "\n\n";
cin >> again;
system("cls");
}
}
}
else if(Icon == 2) // Icon Choice 2
{
for (i=1;i<=1;i++)
{
for (j=1;j<=i;j++);
{
cout << "^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^" << "\n";
cout << Studentfile[0] << "\n";
cout << "^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^" << "\n";
cout << endl;
cout << "\n\n" << "Do you wish to play again? Y/N " << "\n\n";
cin >> again;
system("cls");
}
}
}
else if(Icon == 3) // Icon Choice 3
{
for (i=1;i<=1;i++)
{
for (j=1;j<=i;j++);
{
cout << "###############################################################################" << "\n";
cout << Studentfile[0] << "\n";
cout << "###############################################################################" << "\n";
cout << endl;
cout << "\n\n" << "Do you wish to play again? Y/N " << "\n\n";
cin >> again;
system("cls");
}
}
}
else if(Icon == 4) // Icon Choice 4
{
for (i=1;i<=1;i++)
{
for (j=1;j<=i;j++);
{
cout << "+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++" << "\n";
cout << Studentfile[0] << "\n";
cout << "+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++" << "\n";
cout << endl;
cout << "\n\n" << "Do you wish to play again? Y/N " << "\n\n";
cin >> again;
system("cls");
}
}
}
else // Icon Choice 5
{
cout << "Sorry You Didn't Want to Play" << "\n\n";
cout << "\n\n" << "Do you wish to play again? Y/N " << "\n\n";
cin >> again;
system("cls");
}
}
}
} // End Menu Loop
} // End Main Loop
cout << "Thank you for playing!" << "\n\n";
system("pause");
return 0;
}
Probably because you define menu .. menu5 as int. Try:
char menu = 'y';
char menu2 = 'n';
char menu3 = 'n';
char menu4 = 'n';
char menu5 = 'n';
....
Could someone help me add a loop to my program?
Here's the code:
cout << "What do you do?" "\n";
cout << "\n";
cout << "(Press Enter...)";
cin.ignore();
cout << "\n";
cout << "Stay in bed?" "\n";
cout << "Go to the bathroom?" "\n";
cout << "Go downstairs?" "\n";
cout << "\n";
string answer;
getline(cin, answer);
if (answer == "stay in bed", "Stay in bed")
{
cout << "You lay there, motionless. Silent.";
}
else if (answer == "go to the bathroom", "Go to the bathroom")
{
cout << "You get up and walk across the hall to the bathroom";
}
else if (answer == "go downstairs", "Go downstairs")
{
cout << "You get up and walk downstairs to the kitchen.";
}
else
{
cout << "That is not a valid answer...";
}
cin.ignore();
How should I add a loop to where when user enters something falling under the condition of "else", the loop returns to ask "What do you do?"
There's more than one way to do what you want to do (or what I think you want to do). One way is to put the whole thing inside an endless loop and use break to get out:
while(1)
{
cout << "What do you do?\n";
getline(cin, answer);
if (answer == "stay in bed")
{
cout << "You lay there, motionless. Silent.";
break;
}
else if (answer == "go to the bathroom")
{
cout << "You get up and walk across the hall to the bathroom";
break;
}
}
bool repeatInput = false;
do
{
cout << "What do you do?" "\n";
cout << "\n";
cout << "(Press Enter...)";
cin.ignore();
cout << "\n";
cout << "Stay in bed?" "\n";
cout << "Go to the bathroom?" "\n";
cout << "Go downstairs?" "\n";
cout << "\n";
repeatInput = false;
getline(cin, answer);
if (answer == "stay in bed" || answer == "Stay in bed")
{
cout << "You lay there, motionless. Silent.";
}
else if (answer == "go to the bathroom" || answer == "Go to the bathroom")
{
cout << "You get up and walk across the hall to the bathroom";
}
else if (answer == "go downstairs" || answer == "Go downstairs")
{
cout << "You get up and walk downstairs to the kitchen.";
}
else
{
cout << "That is not a valid answer...";
repeatInput = true;
}
cin.ignore();
}while(repeatInput == true);
using while you can add a loop in your program
#include <iostream>
using namespace std;
int main()
{
while (true) {
cout << "What do you do?" "\n";
cout << "\n";
cout << "(Press Enter...)";
cout << "\n";
cout << "Stay in bed?" "\n";
cout << "Go to the bathroom?" "\n";
cout << "Go downstairs?" "\n";
cout << "\n";
string answer;
getline(cin, answer);
if (answer == "stay in bed", "Stay in bed")
{
cout << "You lay there, motionless. Silent." << endl;
}
else if (answer == "go to the bathroom", "Go to the bathroom")
{
cout << "You get up and walk across the hall to the bathroom" << endl;
}
else if (answer == "go downstairs", "Go downstairs")
{
cout << "You get up and walk downstairs to the kitchen." << endl;
}
else
{
cout << "That is not a valid answer..." << endl;
}
cout << endl;
}
return 0;
}
this code while(true) if the condition is true or 1 the code inside the brackets will execute and if the condition is false or 0 the code will exit the loop
this answer spare of putting break in every else-if function. I used "continue" in hope you will explore c++ language and learn more!
bool check_if_true=true;
while(check_if_true){
cout << "What do you do?" "\n";
cout << "\n";
cout << "(Press Enter...)";
cin.ignore();
cout << "\n";
cout << "Stay in bed?" "\n";
cout << "Go to the bathroom?" "\n";
cout << "Go downstairs?" "\n";
cout << "\n";
string answer;
getline(cin, answer);
if (answer == "stay in bed", "Stay in bed")
{
cout << "You lay there, motionless. Silent.";
}
else if (answer == "go to the bathroom", "Go to the bathroom")
{
cout << "You get up and walk across the hall to the bathroom";
}
else if (answer == "go downstairs", "Go downstairs")
{
cout << "You get up and walk downstairs to the kitchen.";
}
else
{
cout << "That is not a valid answer...";
continue;//return to the start of the while loop
}
cin.ignore();
check_if_true=false;
}
You should use integer identifiers when giving a user options.
#include <iostream>
using namespace std;
int main()
{
int id;
cout << "What do you wanna do?\n" << endl;
cout << "(0) Quit program" << endl;
cout << "(1) Stay in bed" << endl;
cout << "(2) Go to the bathroom" << endl;
cout << "(3) Go downstairs\n" << endl;
while (id != 0)
{
cout << "Choose your option: ";
cin >> id;
switch (id)
{
case 1:
cout << "You lay there, motionless. Silent." << endl;
break;
case 2:
cout << "You get up and walk across the hall to the bathroom." << endl;
break;
case 3:
cout << "You get up and walk downstairs to the kitchen." << endl;
break;
case 0:
cout << "Exitting application!" << endl;
break;
default:
cout << "Error: Invalid option!" << endl;
break;
}
}
return 0;
}
The code is a lot cleaner and easily extensible. You should never have a user input strings when denoting options. The only exception is if you have an underlying program that scans the sentences and derives a course of action from 'keywords' found in the sentence. This is more algorithmic intensive and probably not what you're after, and assuming you are new to C++ I relate to my code in showing that this is the solution that's more practical in your situation. The code was tested, and runs fine.
I'm working on a project which requires some menus to be displayed some of them have sub-menus. So far i have created a function which returns the character that the user has selected, the problem is that after a couple and more back and forth between menus the return value is garbage, it has to do with the cin been flushed but i just can't find the "spot" that is has to be cleared...
I have tried cin.clear(); on various places with mixed results what i'm missing?
Output:
#include <iostream>
#include <string>
#include <vector>
#include <exception>
#include <istream>
using namespace std;
char Menu() {
char ch;
//ch = NULL;
//cin.clear();
cout << "++++++++++++++++++++++++++++++++++++++++++++" << endl;
cout << "+ MAIN MENU +" << endl;
cout << "++++++++++++++++++++++++++++++++++++++++++++" << endl;
cout << "| 1. Enter a new contract. |" << endl;
cout << "| 2. Cancel an active conract. |" << endl;
cout << "| 3. Edit a cotract. |" << endl;
cout << "| 0. Exit |" << endl;
cout << "++++++++++++++++++++++++++++++++++++++++++++" << endl;
cin >> ch;
switch (ch) {
//cin.clear();
case '1':
return ch;
break;
case '2':
return ch;
break;
case '3':
//cin.clear();
cout << "++++++++++++++++++++++++++++++++++++++++++++++++++++++++++" << endl;
cout << "+ -== Edit a cotract ==- +" << endl;
cout << "++++++++++++++++++++++++++++++++++++++++++++++++++++++++++" << endl;
cout << " What would like to edit? |" << endl;
cout << " a) Cover amount. |" << endl;
cout << " b) Add a family memeber.(Applyes to Health insurances) |" << endl;
cout << " 0. Return |" << endl;
cout << "++++++++++++++++++++++++++++++++++++++++++++++++++++++++++" << endl;
cin >> ch;
if(ch == '0') {
//cin.clear();
Menu();
} else if((ch >= 'a') && (ch <= 'b')) {
return ch;
} else {
cout << "Wrong input ! ! !" << endl;
Menu();
return ch;
}
break;
case '0':
cout << "Exiting bye!" << endl;
break;
default:
cout << "Wrong input ! ! !" << endl;
Menu();
break;
}
}
int main() {
char choise;
choise = Menu();
cout << "selected: " << choise << endl;
system("PAUSE");
return 0;
}
default:
cout << "Wrong input ! ! !" << endl;
Menu();
break;
You called another Menu() to fetch input, but didn't return its return value to caller main().
Change it into return Menu();.
I was looking at some code I'm working on, and there are 3-4 errors that I have tried for about a week to get rid of, and I just can't do it! I'm kind of new to programming, so if you could answer in stupid form, that would be great! Here is the code.
#include <iostream>
#include <string>
using namespace std;
int main() {
string password;
int choice;
cout << "Command Line Multi-Tool" << endl;
cout << endl;
cout << "plase enter your password: " << endl;
cin >> password;
if (password == "creeper1") {
cout << endl;
cout << "Main Menu" << endl;
cout << "1. Class Schedule" << endl;
cout << "2. School Info" << endl;
cout << "3. Exit" << endl;
cin >> choice;
}
else {
cout << "Incorrect, Access Denied" << endl;
return(0);
}
}
else (password == "admin1"){
cout << "/*adminLogin=='1'*/" << endl;
cout << endl;
cout << "Menu::Main" << endl;
}
return(0);
}
}
And here is the error log.
/Users/student/Documents/TO BE FILED/Tuesday/main.cpp:31:0 /Users/student/Documents/TO BE
FILED/Tuesday/main.cpp:31: error: expected unqualified-id before 'else'
/Users/student/Documents/TO BE FILED/Tuesday/main.cpp:36:0 /Users/student/Documents/TO BE
FILED/Tuesday/main.cpp:36: error: expected unqualified-id before 'return'
/Users/student/Documents/TO BE FILED/Tuesday/main.cpp:36:0 /Users/student/Documents/TO BE
FILED/Tuesday/main.cpp:36: error: expected declaration before '}' token
Again thanks so much!
You have one if but 2 else brances in your code. Decide which one you want and lose the other one. Looking at the code you probably want
if (password == "creeper1") {
cout << endl;
cout << "Main Menu" << endl;
cout << "1. Class Schedule" << endl;
cout << "2. School Info" << endl;
cout << "3. Exit" << endl;
cin >> choice;
} else if (password == "admin1")
// Your processing code here
} else {
cout << "Incorrect, Access Denied" << endl;
return(0);
}
Unbalanced else,i.e. without a corresponding if.
Perhaps you wanted something like:
if (password == "creeper1") {
}
else if (password == "admin1") {
}
else {
}
You can't use an else if after an else, that block will never be executed.Also, the right syntax is return 0, not return(0).
You also include extra braces, but if you indent the code in the right way you see when a block ends and starts, so you could rarely make mistakes like adding an extra brace:
#include <iostream>
#include <string>
using namespace std;
int main()
{
string password;
int choice;
cout << "Command Line Multi-Tool" << endl;
cout << endl;
cout << "plase enter your password: " << endl;
cin >> password;
if (password == "creeper1")
{
cout << endl;
cout << "Main Menu" << endl;
cout << "1. Class Schedule" << endl;
cout << "2. School Info" << endl;
cout << "3. Exit" << endl;
cin >> choice;
}
else if(password == "admin1")
{
cout << "/*adminLogin=='1'*/" << endl;
cout << endl;
cout << "Menu::Main" << endl;
}
else
{
cout << "Incorrect, Access Denied" << endl;
return 0;
}
return 0;
}
This is the code with all the syntax errors fixed.About semantics I don't know if it works, but now you can compile and execute it, to test the code.
becasue else cannot comprise judgement
the correct usage is like this:
if(password == "creeper1"){
}
else if(password == "admin1"){
}
else{
}