After the call for Back to Main Menu, it returns to the mainMenu but when option or command is typed, the option is not accepted or the loop not working. Wonder where is the mistake? Is it extra call should be added or?
#include <iostream>
using namespace std;
char mainMenu(void);
int factorial(int n);
unsigned long long combination(long nK, long nR);
int main(){
char option;
int shape,function,i,j,k,t,n;
long nK, nR;
unsigned long long COM;
while((option=mainMenu())!='0')
{
switch(option)
{
case '1'://Program 1:
cout<< "*Drawing a shape\n"
<< "(1-Rectangle, 2-Triangle, 3-Inverted Triangle, 4-Letter 'H', 0-Back to Main Menu)\n";
do
{
cout<< "Choose shape >> ";
cin>> shape;
cout<< endl;
switch(shape)
{
case 1: break;
case 2: break;
case 3: break;
case 4: break;
case 0:
//Back to Main Menu
cout<< "Back to main menu\n"
<< endl;
return mainMenu(); //After here, it does back to Main Menu but command or option is not working
}
}while(shape!=0);
case '2': //Program 2
cout<< "*Choose function of calculator\n"
<< "(1-Factorial, 2-Combination, 0-Back to main menu)\n";
do
{
cout<< "Choose function >> ";
cin>> function;
cout<< endl;
switch(function)
{
case 1: break;
case 2: break;
case 0:
cout<< "Back to main menu\n"
<< endl;
return mainMenu();
}
}while(function!=0);
case '0':
cout<< "Program is terminating\n"
<< endl;
return 0;
default:
cout<< "Wrong input. Please choose one of the above options.\n"
<< endl;
return mainMenu();
}
}
}
char mainMenu(void){
char option;
cout<< "##############################\n"
<< "Main Menu\n"
<< "Enter your command!\n"
<< "##############################\n"
<< endl
<< "1. Program1\n"
<< "2. Program2\n"
<< "0. Exit\n"
<< endl
<< "Command >> ";
cin>> option;
cout<< endl;
return option;
}
I'm not sure what your question is, but your code is missing 2 important things. First, you need break statements at the end of each case block, otherwise the program flow will continue on to the next case statement.
Second, the inner menu doesn't ever escape the inner while(1) loop. This is a possible case for a goto use, although in practice it would better to refactor the code to split the top menu and inner menu into two functions, and use a return in the inner menu to return to the outer menu.
I'm not sure what your question is, but your code is missing 2 important things. First, you need break statements at the end of each case block, otherwise the program flow will continue on to the next case statement.
Second, the inner menu doesn't ever escape the inner while(1) loop. This is a possible case for a goto use, although in practice it would better to refactor the code to split the top menu and inner menu into two functions, and use a return in the inner menu to return to the outer menu.
As said, you're code is missing various things. It would be awesome if you distribute the entire code, and additionally the exact error message with line.
void value not ignored as it ought to be?...
...Is not that much of an explanation...
Also, are you sure you included iostream?
#include iostream
That said, you did not declare any of the variables used in the program.
You also missed a space in line 2 of your mainMenu() function.
Also, please tell us what you expected to happen.
Related
I have a do while loop which consists of two switch statements, some output code and some nested while loops to check for input errors. The thing is I want to break the switch statement when the user inputs 'Q' for quit and skip the rest of the code. So I've essentially got two problems.
If i use a do while, then it turns into being a return 0 and a boolean flag while(true) which logically goes against itself.
if i drop the do while and only use return 0, the code can't be executed multiple times.
I've come to terms with this being a flow problem rather than a syntax problem and was wondering how I should structure the flow to make it "clean code".
A quick example:
do {
char answer;
cout << "Type answer: ";
cin >> answer;
switch (answer) {
case A:
cout << "hello";
break;
case B:
cout << "more weird output";
break;
case Q:
cout << "Goodbye";
return 0;
}
cout << "more useless output that I want to skip";
cout << "how does this even work";
} while (run);
Here I've a return 0 which completely negates the need for a while(run) flag. This is bad coding practice I've been told, so I was wondering how one would go about structuring this in a good manner?
Here I think i fixed the code. Make sure you are typing a capital Q not lowercase. Also you forgot ' ' around your chars. Your logic was right - just small errors :) Goodluck!
#include <iostream>
using namespace std;
int
main ()
{
bool run = true;
do
{
char answer;
cout << "Type answer: ";
cin >> answer;
switch (answer)
{
case 'A':
cout << "hello";
break;
case 'B':
cout << "more weird output";
break;
case 'Q':
cout << "Goodbye";
return 0;
}
cout << "more useless output that I want to skip";
cout << "how does this even work";
}while (run);
return 0;
}
I am currently getting to grips with how to correctly implement multiple functions in my programs and I think I have got the right idea but I am just wanting to clarify.
When putting some logic into a particular function, should I be handling the end the result in that function or bringing it back to my "main function"? I am aware this is probably an ambiguous question so I have posted my code here to try and help matters.
The program simply adds a string to a vector but I am wondering whats the best approach to handle it.
Thank you so much in advance.
Program 1.
std::vector<std::string> favouriteGames; //Stores favourite games
int menu = 0; //Menu navigation
std::cout << "1: Add Game. 2: Remove Game. 3: List Games. 4: Exit.";
std::cin >> menu;
//Menu
switch (menu)
{
case 1:
favouriteGames.push_back(AddGame());
break;
case 2:
//favouriteGames.erase(RemoveGame);
break;
case 3:
//ListGames();
break;
case 4:
break;
default:
std::cout << "Please enter correct data.";
}
//Add game
std::string AddGame()
{
std::string gameName;
int menu = 0;
std::cout << "Enter name of game you wish to add.";
std::cin >> gameName;
return gameName;
}
Program 2.
Or like this when the function is solely handling the data and doesn't return anything.
void AddGame(std::vector<std::string> favouriteGames);
int main()
{
std::vector<std::string> favouriteGames; //Stores favourite games
int menu = 0; //Menu navigation
std::cout << "1: Add Game. 2: Remove Game. 3: List Games. 4: Exit.";
std::cin >> menu;
//Menu
switch (menu)
{
case 1:
AddGame(favouriteGames);
break;
case 2:
//favouriteGames.erase(RemoveGame);
break;
case 3:
//ListGames();
break;
case 4:
break;
default:
std::cout << "Please enter correct data.";
}
//Keep Window open
std::string barn;
std::cin >> barn;
return 0;
}
//Add game
void AddGame(std::vector<std::string> favouriteGames)
{
std::string gameName;
int menu = 0;
std::cout << "Enter name of game you wish to add.";
std::cin >> gameName;
favouriteGames.push_back(gameName);
}
Program I.
In general, your functions should have one job. It makes them re-usable and helps to keep your interfaces clean and stable.
In this case, that means your function is actually named wrongly. It should be something like requestGameName().
You could then also hive the .push_back into its own, second function (addGame()?) though that may be overkill in your initial version. Still, one day, adding a game may involve more lines of code that trigger you to move all of that into another function.
I am currently testing out my driver program for my homework. What happens is that I have a menu printed with different options, and the program uses a switch statement based on the user's input to determine what to do. Everything works fine except for the "exit program" case, where it's supposed to leave the program and end it. Instead, it will print out the message "Quitting program" (like it's supposed to) and then follow up with doing one of the first 4 cases. It doesn't actually leave the switch statement. I don't know what could be wrong because I've used this method before and have not encountered this issue.
#include <iostream>
#include <fstream>
#include <cstring>
#include <string>
#include "ListRecords.h"
#include "BookRecord.h"
using namespace std;
//Prints the menu for the user.
void printMenu(){
cout << "\n\n1) Insert a book record into the list\n";
cout << "2) Print information of a book with the given ISBN number\n";
cout << "3) Print the list of books, sorted by ISBN (lowest to highest)\n";
cout << "4) Print the list of books, sorted by title\n";
cout << "5) Quit the program\n";
cout << "Option: ";
}
//Menu block of the code. Takes in command choice and performs appropriate functions
void action(ListRecords books, int x){
cin.sync();
int option;
switch (x){
case 0: {
printMenu();
cin >> option;
action(books, option);
}
case 1: {
string title, author, pub;
long isbn;
cout << "\n\t**Inserting a new book into the record**";
cout << "\nTitle: ";
getline(cin, title);
cout << "Author: ";
getline(cin, author);
cout << "Publisher: ";
getline(cin, pub);
cout << "ISBN: ";
cin >> isbn;
BookRecord sample = BookRecord(title, author, pub, isbn);
books.insertBookInfo(sample);
cout << "\n\tNew book has been entered into the record\n\n";
printMenu();
cin >> option;
action(books, option);
}
case 2: {
long printISBN;
cout << "Printing book with ISBN number: ";
cin >> printISBN;
books.printBookInfo(printISBN);
cout << "\n\n";
printMenu();
cin >> option;
action(books, option);
}
case 3: {
cout << "\n\t**Printing all books in ISBN increasing order**\n";
//books.quickSortNum(0, books.seeFillSize());
books.rearrangeList(0);
books.printAll();
printMenu();
cin >> option;
action(books, option);
}
case 4: {
cout << "\n\t**Printing all books in alphabetical order**\n";
//books.quickSortNum(0, books.seeFillSize());
books.rearrangeList(1);
books.printAll();
printMenu();
cin >> option;
action(books, option);
}
case 5: {
cout << "\n\t**Quitting program. . .**\n";
return;
}
//For the purposes of debugging, I placed option 6 to print all books
case 6: {
books.printAll();
printMenu();
cin >> option;
action(books, option);
}
default: {
cout << "\n\t**ERROR: Invalid input. Try again**\nEnter option: ";
cin >> option;
action(books, option);
}
}
}
int main(void){
string fileName;
int option;
//Prompt for file name
cout << "Enter the name of the file: ";
cin >> fileName;
cout << "\nLoading the file and its contents. . .";
//Create a List Records object and clear stream
ListRecords books = ListRecords(fileName);
cin.sync();
cout << "\n\n";
//Start menu process. Beginning option is 0
action(books, 0);
//Once user quits, this will happen
cout << "\n Thanks for trying out this program!\n";
system("pause");
return 0;
}
The root cause of your problem is that your code uses recursion instead of iteration.
main makes a call to action, which goes into a switch, which then calls action again, which goes into the switch and calls action, until the Quit option is selected.
At this point the recursive call chain starts to unwind. Unfortunately, since your code lacks break statements, the switch is not exited immediately. Instead, the code falls through to the next case label, making you think that the return did not do its job at terminating the action. It did, but only the last action on the call stack is terminated. The remaining ones are still in progress, so they would continue as soon as the higher-level action finishes.
You can add break statements to your switch statement to mask the problem. However, the root cause would not go away: your program would remain poorly organized, and hard to read.
Consider rewriting the code using a while loop in the action function. Keep the switch, add breaks, and remove recursive calls to action from inside the switch. Instead, let the loop continue, so that the switch is re-entered and processed again, until the Quit option is selected.
First thing you do is call action(books, 0); to get to the menu.
switch (x){
case 0: {
printMenu();
cin >> option;
action(books, option);
}
There you call action(books, option); with the user supplied number.
You continue doing this for every option untill the user enters a 5 to end the program.
Because you don't have any break statements the code will go back to the 'calling case' and continue executing into the next case.
Be sure to end a case with a break to not continue executing the next case block (fall through).
Here is another questionn about why a break is needed.
In main() you call action(book, 0) so it enters action function. Then you prompt for choice and enter action() gain with that option. Then you enter 5 and quit that action, the return address of the nested action() call returns just after that call, at case 1: block and continues to execute it.
So what you need to do is put break statement at the end of each block.
When you don't use break after once case block, the code continues executing next case block.
So as the guy above said, you should consider placing break at the end of each block.
Also, you might want to consider not using recursion, but maybe iteration, and put prompt block outside the switch/case.
I'm totally new and I don't know how else to ask this or what to even search for.
The case is this: I want to navigate through a menu with several sub-menus. In this example I'll just use "options" and a "game" to illustrate what I mean. Say you have a menu with 3 options.
1 - Start
2 - Options
3 - Quit
Choosing options should take you to another menu. Which would then look something like
1 - Difficulty
2 - Sound
3 - Back
Depending on where you go from here, there will be more sub menus obviously.
I've tried nesting do-while loops and all kinds of things but I just don't have enough understanding to know what it is I'm doing wrong.
Here is what I have so far:
#include <cstdlib>
#include <iostream>
using namespace std;
int main(int argc, char *argv[])
{
int choice;
do{
cout << "Main Menu\n";
cout << "Please make your selection\n";
cout << "1 - Start game\n";
cout << "2 - Options\n";
cout << "3 - Quit\n";
cout << "Selection: ";
cin >> choice;
switch(choice) {
case 1:
cout << "Pew pew!\n";
break;
case 2:
cout <<"????\n";
break;
case 3:
cout << "Goodbye!";
break;
default:
cout << "Main Menu\n";
cout << "Please make your selection\n";
cout << "1 - Start game\n";
cout << "2 - Options\n";
cout << "3 - Quit\n";
cout << "Selection: ";
cin >> choice;
}
} while(choice !=3);
system("PAUSE");
return EXIT_SUCCESS;
}
Which works like a regular menu. But I have no idea where to go from here. I consulted some books, but finding anything even remotely related to this was completely random. Any help or examples would be greatly appreciated.
What happened with nesting tons of loops just made all loops execute simultaneously every time. How do I keep this from happening? Making more choices? (choice1-2-3 etc ? or what?)
Ok guys. Thanks for all the help. This is what I ended up with in the end.
It runs as I want it to and by max_'s example and Mike B's commentary I think this works pretty well.
Thanks alot everyone =)
#include <iostream>
#include <cstdlib>
using namespace std;
void menu();
void mainMenu();
void optionsMenu();
void options();
int choice1 = 0;
int choice2 = 3;
int main(int argc, char** argv) {
menu();
return 0;
}
void menu(){
do {
choice2 = 0;
mainMenu();
switch(choice1) {
case 1:
cout << "Pew pew!\n";
break;
case 2:
options();
break;
case 3:
break;
}
} while(choice1 != 3);
}
void options(void) {
do {
optionsMenu();
switch(choice2){
case 1:
cout << "So difficult!\n";
break;
case 2:
cout << "Beep!\n";
break;
case 3:
break;
default:
break;
}
} while(choice2 != 3);
}
void mainMenu(void) {
cout << "Main Menu\n";
cout << "1 - Start game\n";
cout << "2 - Options\n";
cout << "3 - Quit\n";
cout << "Please choose: ";
cin >> choice1;
}
void optionsMenu(void) {
cout << "Options Menu\n";
cout << "1 - Difficulty\n";
cout << "2 - Sound";
cout << "3 - Back\n";
cout << "Please choose: ";
cin >> choice2;
}
How about this (dunno if it compiles though):
#include <cstdlib>
#include <iostream>
using namespace std;
int GetInput()
{
int choice;
cin >> choice;
return choice;
}
void DisplayMainMenu()
{
cout << "Main Menu\n";
cout << "Please make your selection\n";
cout << "1 - Start game\n";
cout << "2 - Options\n";
cout << "3 - Quit\n";
cout << "Selection: ";
}
void DisplayOptionsMenu()
{
cout << "Options Menu\n";
cout << "Please make your selection\n";
cout << "1 - Difficulty\n";
cout << "2 - Sound\n";
cout << "3 - Back\n";
cout << "Selection: ";
}
void Options()
{
int choice = 0;
do
{
system("cls");
DisplayOptionsMenu();
choice = GetInput();
switch(choice)
{
case 1:
cout << "difficulty stuff";
break;
case 2:
cout << "sound stuff";
break;
case 3:
break;
default:
break;
}
} while(choice!=3);
}
int main(int argc, char *argv[])
{
int choice = 0;
do
{
system("cls");
DisplayMainMenu();
choice = GetInput();
switch(choice) {
case 1:
cout << "Pew pew!\n";
break;
case 2:
Options();
break;
case 3:
cout << "Goodbye!";
break;
default:
break;
}
} while(choice!=3);
system("PAUSE");
return EXIT_SUCCESS;
}
I'd recommend that you change a few things here. Are you familiar with object-oriented design? If not, it's highly recommended that you read about that if you're looking to write code in C++ (Or just writing code in general, as it's a pretty major aspect of many programming languages)
Consider treating each of your menus and submenus as individual objects. Each time you enter the loop, use an object pointer to call a method that prints the current menu text.
Then, take the input from the user as normal, and change the menu object you're using now.
This is perhaps not the most ideal way to do a console menu, but it will give you a very strong grounding in how objected-oriented programming works.
I've attached an example :
#include <iostream>
#include <string>
class BaseMenu
{
public:
BaseMenu() { m_MenuText = "This shouldn't ever be shown!"; } // This is the constructor - we use it to set class-specific information. Here, each menu object has its own menu text.
virtual ~BaseMenu() { } // This is the virtual destructor. It must be made virtual, else you get memory leaks - it's not a quick explaination, I recommend you read up on it
virtual BaseMenu *getNextMenu(int iChoice, bool& iIsQuitOptionSelected) = 0; // This is a 'pure virtual method', as shown by the "= 0". It means it doesn't do anything. It's used to set up the framework
virtual void printText() // This is made virtual, but doesn't *have* to be redefined. In the current code I have written, it is not redefined as we store the menu text as a string in the object
{
std::cout << m_MenuText << std::endl;
}
protected:
std::string m_MenuText; // This string will be shared by all children (i.e. derived) classes
};
class FirstMenu : public BaseMenu // We're saying that this FirstMenu class is a type of BaseMenu
{
FirstMenu()
{
m_MenuText = "Main Menu\n" // What we are doing here is setting up the string to be displayed later
+ "Please make your selection\n" // What we are doing here is setting up the string to be displayed later
+ "1 - Start game\n" // What we are doing here is setting up the string to be displayed later
+ "2 - Options\n" // What we are doing here is setting up the string to be displayed later
+ "3 - Quit\n" // What we are doing here is setting up the string to be displayed later
+ "Selection: "; // What we are doing here is setting up the string to be displayed later
}
BaseMenu *getNextMenu(int choice, bool& iIsQuitOptionSelected) // This is us actually defining the pure virtual method above
{
BaseMenu *aNewMenu = 0; // We're setting up the pointer here, but makin sure it's null (0)
switch (choice) // Notice - I have only done "options". You would obviously need to do this for all of your menus
{
case 2:
{
aNewMenu = new SecondMenu; // We're creating our new menu object here, and will send it back to the main function below
}
case 3:
{
// Ah, they selected quit! Update the bool we got as input
iIsQuitOptionSelected = true;
}
default:
{
// Do nothing - we won't change the menu
}
}
return aNewMenu; // Sending it back to the main function
}
};
class SecondMenu : public BaseMenu
{
SecondMenu()
{
m_MenuText = "OptionsMenu\n"
+ "Please make your selection\n"
+ "1 - ????"
+ "2 - dafuq?";
}
BaseMenu *getNextMenu(int choice, bool& iIsQuitOptionSelected) // This is us actually defining the pure virtual method above
{
BaseMenu *aNewMenu = 0; // We're setting up the pointer here, but makin sure it's null (0)
switch (choice) // Notice - I have only done options. You would obviously need to do this for all of your menus
{
case 1:
{
aNewMenu = new FirstMenu; // We're creating our new menu object here, and will send it back to the main function below
}
break;
case 2:
{
aNewMenu = new FirstMenu; // We're creating our new menu object here, and will send it back to the main function below
}
break;
default:
{
// Do nothing - we won't change the menu
}
}
return aNewMenu; // Sending it back to the main function
}
};
int main (int argc, char **argv)
{
BaseMenu* aCurrentMenu = new FirstMenu; // We have a pointer to our menu. We're using a pointer so we can change the menu seamlessly.
bool isQuitOptionSelected = false;
while (!isQuitOptionSelected) // We're saying that, as long as the quit option wasn't selected, we keep running
{
aCurrentMenu.printText(); // This will call the method of whichever MenuObject we're using, and print the text we want to display
int choice = 0; // Always initialise variables, unless you're 100% sure you don't want to.
cin >> choice;
BaseMenu* aNewMenuPointer = aBaseMenu.getNextMenu(choice, isQuitOptionSelected); // This will return a new object, of the type of the new menu we want. Also checks if quit was selected
if (aNewMenuPointer) // This is why we set the pointer to 0 when we were creating the new menu - if it's 0, we didn't create a new menu, so we will stick with the old one
{
delete aCurrentMenu; // We're doing this to clean up the old menu, and not leak memory.
aCurrentMenu = aNewMenuPointer; // We're updating the 'current menu' with the new menu we just created
}
}
return true;
}
Note that this might be a bit complex for starting out. I strongly recommend you read the other answers people have posted. It should give you a few approaches on how to do it, and you can progress from the basic up to the more complex, examining each change.
Looking at what you are trying to do, I would change how you are ensuring the user still want's to play the game first. Look at using a while loop to check if a variable is true or false (people tend to use boolean variables(bool's) for this, an int set to 1 or 0 will do the same). That removes the need for the do-while. Reading up on control logic (if/else, while, for loops) and logical operators (&& - and, || - or, != - not equal to) is recommended. Control logic makes your code do different things, booleans are quick for checking yes/no scenarios and logical operators allow you to check multiple items in one if statement.
Some reading: Loops
Edit: Have more links for reading material, don't have the rep to post them.
Secondly, use another variable (int or whatever suits you) to track what screen you are on.
Based on this selection, display different options but still take input 1,2,3 to decide upon the next action.
In some terrible pseudo-code here is what I would lean towards:
main()
{
int choice
int screen = 1
bool running = true
while(running) {
//Screen 1, Main menu
if(screen == 1) {
cout << stuff
cout << stuff
cout << option 1
cout << option 2
cout << option 3
cout << selection:
cin >> choice
}
else if(screen == 2){
//options screen here
}
else {
//default/error message
}
//add some choice logic here
if(screen == 1 && choice == 3){
//being on screen one AND choice three is quit
running = false;
}
else if(screen == 1 && choice == 2){
//etc..
}
}
}
This is my first proper answer, all terrible criticism is well recieved.
Hey can anyone see what wrong with my menu in the while loop it keeps printing out dixie if i press 1 in an unlimited loop. I have a while loop around the menu so that the menu is always there for the user to go back through choices.
here is my code:
#include <iostream>
using namespace std;
int main()
{
int choice;
bool menu = true;
cout <<"========Welcome to the database menu========\n";
cout << "Press 1 to insert a new record at a particular position\n"
"Press 2 to delete a record from a particular position\n"
"Press 3 to search the database and print results\n"
"Press 5 to find the average experience points of players at a particular level\n"
"Press 6 to find and remove all duplicate entries\n"
"Press 0 to quit\n\n\n\n\n\n\n\n\n";
cout << "Choice: ";
cin >> choice;
//*****************************************************************************
// Switch menu to display the menu.
//*****************************************************************************
while(menu)
{
switch (choice)
{
case 1:
cout << "dixie";
break;
case 2:
cout << "bexie";
break;
default:
cout<< "That is not a choice!!!\n";
}
}
getchar();
getchar();
}
There is no code that can change either menu or choice inside your while loop. So once it gets going, it will never stop.
It says while (menu) and that means it'll keep doing that until you set menu to false.
Also, I think you want to add the cin >> choice in the loop, or it'll just repeat the selection again and again.
I would suppose the while loop should include printing the menu options and having the user select an option like so:
while (menu)
{
cout <<"========Welcome to the database menu========\n";
cout << "Press 1 to insert a new record at a particular position\n"
"Press 2 to delete a record from a particular position\n"
"Press 3 to search the database and print results\n"
"Press 5 to find the average experience points of players at a particular level\n"
"Press 6 to find and remove all duplicate entries\n"
"Press 0 to quit\n\n\n\n\n\n\n\n\n";
cout<< "Choice: ";
cin>> choice;
switch (choice)
{
case 1:
cout << "dixie";
break;
case 2:
cout << "bexie";
break;
default:
cout<< "That is not a choice!!!\n";
}
}
Another possibility would be to start the while loop just before the cout << "Choice: " line.
menu variable is always true inside the loop. It's the same as while(true) at the moment.