Exiting the Game from the Menu is not working - c++

So I have a Menu that I used to run my text based game. The problem is that I can't seem to exit my game.Every time I run it, I can do option 1 and go to my game, and options 2 and 3 work just fine. But For option 4, I am unable to exit my game. All it does is print out what I ask it to print out, before giving the menu options again (as if it was just looping).
I have googled a lot, and tried to figure out why but I am not sure.
If someone can advise me what to do or tell me where my mistake is, it would be greatly appreciated. Please let me know if you want to see more code. All I have displayed here is the Menu Function.
void menu() {
char choice = -1;
while(choice != '1')
{
cout << "\n* * * * *" << endl;
cout << " The Dark Maze\n";
cout << "\n* * * * *" << endl;
cout << "\n=====================";
cout << "\n Main Menu |";
cout << "\n=====================";
cout << "\n 1 - Start Game |";
cout << "\n 2 - Instructions |";
cout << "\n 3 - Storyline |";
cout << "\n 4 - Exit |";
cout << "\n=====================";
cout << "\n";
cout << "\n Enter choice: ";
cout << "\n";
cin >> choice;
switch (choice)
{
case '1':
cout << "\n" << endl;
cout << "\n But we can't start the game just yet..." << endl;
break; //heads to game
case '2':
Instructions();
break;
case '3':
Storyline();
break;
case '4':
cout << "\n Well, if you really don't want to play... you don't have to." << endl;
break; //just say exit?? break isnt making it stop
default:
cout << "Invalid Character entered\n";
cout << "\n";
cout << "Press Space to continue\n";
}// end of switches
cin.get();
} // end of while
}// end of menu

You shouldn't be using while loop for this. Try do-while loop for this kind of menus like this:
do
{
// your menu here...
cin >> choice;
switch ( choice )
{
case ...
...
}
// cin.get();
// ^^^^^^^^^^ You don't need this...
} while ( choice != '4' );
Some points to help you:
Use an enum to define your menu choices. (OR an enum class).
You can simply write a printMenu() function to print the menu in the main loop. Another function to process the choice.
For example:
void startGame()
{
char choice = INVALID_OPTION; // INVALID_OPTION => default invalid value
do
{
printMenu();
cin >> choice;
processChoice( choice );
} while ( choice != EXIT ); // EXIT => #define or an enum
}

You can use exit() to terminate your program with a given return value:
case '4':
std::cout << "blahblahblah";
std::exit(0);
break; // No longer necessary
It's prerequisite and prototype is
#include <cstdlib>
namespace std{
void exit(int status);
}

just use return instead break blow case '4' . not perfect but can work.

Related

Problem typing a letter when expecting a number in C ++

I am making a program which consists of making a menu to register and delete products from a store, I am just designing the menu with a switch, everything works fine up to there, the problem is that when I enter something other than a number as data ( letter or symbol) the console goes crazy; all the text starts to blink and it won't let me do anything (as if it was in a loop) and I have to close it.
Is there any way to avoid this? So when I enter a letter or symbol, it automatically detects it as invalid and shows me the message without the console going crazy?
By the way, I use Visual Studio.
Thanks in advance :)
#include<iostream>
#include<locale.h>
using namespace std;
int main()
{
int opc;
cout << " WELCOME TO THE STORE \"Happy Shopping\" ";
cout << endl;
cout << "\n1.- Create Order.";
cout << "\n2.- Delate Order.";
cout << "\n3.- list of orders created.";
cout << "\n4.- Exit";
cout << endl;
cout << "\n¿what do you want to do?: "; cin >> opc;
switch (opc)
{
case 1:cout << "\nCreate Order"; break;
case 2:cout << "\nDelate Order"; break;
case 3: cout << "\nlist of orders created"; break;
case 4:exit(EXIT_SUCCESS);
default:
if ((opc != 1) && (opc != 2) && (opc != 3) && (opc != 4))
{
system("cls");
cout << "the option entered is not valid, try again";
return main();
}
}
}
Maybe don't return main?
switch (opc)
{
case 1:cout << "\nCreate Order"; break;
case 2:cout << "\nDelate Order"; break;
case 3: cout << "\nlist of orders created"; break;
case 4:exit(EXIT_SUCCESS);
default:
system("cls");
cout << "the option entered is not valid, try again";
}
If you make opc a string and take input as a string, you can manually check if the string is a number like so:
cin >> opc;
if (!isdigit(opc[0]) // since you're dealing with single-digit numbers, this should be fine
{
cout << "You didn't enter a number!\n";
// Any other error handling
}
isdigit is a function located in the cctype header file, so you should add #include <cctype> at the beginning of the file.
After this, you can convert opc to an integer with stoi():
int opnum = stoi(opc);
// opnum is now the number, write the rest of the code such that it uses opnum
As already said, you should not return main(). You may use a loop by testing your input for instance (surely one of the many solutions that may exist).
Also, you do not need the portion of code below :
// you do not need the if as you are already in the case !=1,2,3, or 4
if ((opc != 1) && (opc != 2) && (opc != 3) && (opc != 4))
I provided you with an attempt, taken from your code, that may help to improve your code.
There might still be some bugs but it is a good starting point
#include<iostream>
#include<locale.h>
int main()
{
int opc=0;
std::string input;
std::cout << " WELCOME TO THE STORE \"Happy Shopping\" ";
std::cout << std::endl;
// first display
std::cout << "\n1.- Create Order.";
std::cout << "\n2.- Delate Order.";
std::cout << "\n3.- list of orders created.";
std::cout << "\n4.- Exit";
std::cout << std::endl;
std::cout << "\n¿what do you want to do?: "; //cin >> opc;
std::cin >> input;
while ( input.length() > 0 )
{
// if we enter a string of more than length 1
try
{
opc = std::stoi( input );
}
catch (...)
{
// mainly if the converted argument is not a number =>std::invalid_argument
std::cout << "invalid value " << opc << std::endl;
}
std::cout << "you entered the value " << opc << std::endl;
switch (opc)
{
case 1:
std::cout << "\nCreate Order";
break;
case 2:
std::cout << "\nDelate Order";
break;
case 3:
std::cout << "\nlist of orders created";
break;
case 4:
exit(EXIT_SUCCESS);
default:
// you do not need the if as you are already in the case !=1,2,3, or 4
//if ((opc != 1) && (opc != 2) && (opc != 3) && (opc != 4))
//{
system("cls");
// if you type things other than
std::cout << "\n1.- Create Order.";
std::cout << "\n2.- Delate Order.";
std::cout << "\n3.- list of orders created.";
std::cout << "\n4.- Exit";
std::cout << std::endl;
std::cout << "\n¿what do you want to do?: "; //cin >> opc;
}
std::cin >> input;
}
}

holeMenuProgram.cpp:38:1 Error: Expected Primary-Expression before '}' token

I am creating a menu using switch cases but when I got to filter out unavailable choices using a do-while statement I am getting an odd error. Could I get some insight on what I am doing wrong here? Thank you in advance as I am a new programmer. I am aware the case switches have nothing in them but this shouldn't stop it from compiling correctly.
//Programmer: Lane Floyd Date: 2/17/2020
//File: holeMenuProgram.cpp
//Description:
#include <iostream>
using namespace std;
int main()
{
int menuChoice; //User input 1-4 for menu choice.
do
{
// Below is the menu.
cout << " Menu " << endl;
cout << " ---- " << endl;
cout << "1. Enter a number " << endl;
cout << "2. Power the number " << endl;
cout << "3. Cube root of the number " <<endl;
cout << "4. Quit" <<endl;
cout << "Input Choice: \r";
cin >> menuChoice;
} while (menuChoice != 1 || menuChoice != 0);
switch(menuChoice)
{
case 1:
case 2:
case 3:
case 4:
}
return 0;
}
A label must precede a statement. You could write for example
switch(menuChoice)
{
case 1:
case 2:
case 3:
case 4:
;
}
placing a null statement before the closing brace in the switch statement.
Or to make the code more readable you could insert at least one break statement like
switch(menuChoice)
{
case 1:
case 2:
case 3:
case 4:
break;
}

How to make a program loop forever until a certain case in a switch statement is met?

How can I make this program loop forever unless the user chooses 'C' in the switch statement? I've tried several things on my own that didn't seem to work and I am not sure how to proceed, since I am still sort of a beginner in C++. Can anyone help? Let me know if you need additional info.
#include <iostream>
using namespace std;
int main()
{
cout << "Hello user, what do you want to do: " << endl
<< "A. Display A Message" << endl
<< "B. Perform A Calculation" << endl
<< "C. Exit The Program" << endl;
int result = 80 + 10;
char answer;
cin >> answer;
switch (answer)
{
case 'A':
cout << "Welcome to C++!" << endl;
break;
case 'B':
cout << 80 << " + " << 10 << " = " << result << endl;
break;
case 'C':
cout << "Goodbye...." << endl;
break;
return 0;
}
}
(Currently your return 0; statement is unreachable.)
The simplest way is to use a for(;;) infinite loop idiom, and a return in the case 'C' case in place of the break:
for (;;){
char answer;
cin >> answer;
switch (answer){
case 'A':
cout << "Welcome to C++!" << endl;
break;
case 'B':
cout << 80 << " + " << 10 << " = " << result << endl;
break;
case 'C':
cout << "Goodbye...." << endl;
return 0;
}
}
The break statements take program control out of the switch but not the loop.
We tend to use for(;;) over alternatives such as while(true) since many compilers accept the former without a warning.
Or
bool finished=false;
while (!finished)
{
switch (something)
{
case foo:
finished = true; break;
...
}
}
Or one of a dozen ways to achieve the same thing ;)

switch statement C++ [default part]

I'm writing a basic program about switch statement. The menu of 5 selections, if the use input invalid number, the user should be prompted again to make a selection (range is from 1-5). Here what I got so far:
#include <iostream>
#include "Menu.h"
using namespace std;
void Menu::inputChoices()
{
int choice;
cout << "IHCC Computer Science Registration Menu" << endl;
cout << "1. Welome to Computer Programming in C++" << endl;
cout << "2. Welcome to Java Programming" << endl;
cout << "3. Welcome to Android Programming" << endl;
cout << "4. Welcome to iOS Programming" << endl;
cout << "5. Exit" << endl;
cout << "\nEnter your selection: " << endl;
while ((choice = cin.get()) != EOF)
{
switch (choice)
{
case '1':
cout << "Welcome to Computer Programming in C++" << endl;
break;
case '2':
cout << "Welcome to Java Programming" << endl;
break;
case '3':
cout << "Welcome to Android Programming" << endl;
break;
case '4':
cout << "Welcome to iOS Programming" << endl;
break;
case '5':
cout << "Exiting program" << endl;
break;
default:
cout << "Invalid input. Re-Enter your selection: " << endl;
}
}
}
This project has 3 files, this is the source file. My problem is when I input a number is in the range (1-5), the default part of switch still also shows up. I just want show up my selection. Can anyone help me please! Thank you very much
The reason why you are also getting the default value is because cin.get() is reading the newline character (10).
I don't think using cin.get makes sense here since entering something like 23987928 or asdasf will output a ton of lines... You should use cin >> choice and convert your cases into ints. Something like:
cin >> choice;
switch (choice)
{
case 1:
cout << "Welcome to Computer Programming in C++" << endl;
break;
// ...
default:
cout << "Invalid input. Re-Enter your selection: " << endl;
}
The enter key '\n' should be handled. Try following and see if it works:
while ((choice = cin.get()) != EOF)
{
case 1:
// ...
// Basic idea is read extra `\n` and ignore it. Use below if condition
default:
if(choice != '\n')
cout << "Invalid input. Re-Enter your selection: " << endl;
}

C++, getting a infinite loop

i try to do a simple menu using switch. I also want to do a check if the user made a valid input (Only int from 1 to 4). Entering -4 or 44 is working fine with this check. But if i enter something like "w" it gives me a infinite loop.
I'm guessing i need another if / else with if (!cin) blabla else go ahead with switch.
But i'm not sure how i do that the else is starting the switch.
int menu() {
int enter;
bool exit = false;
do {
cout << "Wie soll angefangen werden: " << endl; //Enter your choice
cout << "1 - Spiel starten" << endl; // do game();
cout << "2 - Highscore " << endl; //do score();
cout << "3 - Quiz starten " << endl; //do quiz();
cout << "4 - Ende " << endl; //end the programm
cin >> enter;
switch (enter) {
case 1:
game();
break;
case 2:
score();
break;
case 3:
showQuizDialog();
break;
case 4:
exit = true;
break;
default:
cout << "Keine gültige Eingabe, nochmal: " << endl; //invalid input, again
void flushCin();
} //end of switch
} while (exit == false);
}//end of menu();
It's because the input is trying to get an integer. When the input is not an integer, the input is left in the buffer, so next time around in the loop the same input is still there.
Also, you are not calling the flushCin function in the default case, you are declaring it. You might want to remove the void keyword. I guess it does the correct thing? (I.e. calling std::cin.ignore() and std::cin::clear().)
Read into a string and try to convert to int:
#include <sstream>
#include <string>
using namespace std;
int menu() {
int enter;
string str;
bool exit = false;
do {
cout << "Wie soll angefangen werden: " << endl; //Enter your choice
cout << "1 - Spiel starten" << endl; // do game();
cout << "2 - Highscore " << endl; //do score();
cout << "3 - Quiz starten " << endl; //do quiz();
cout << "4 - Ende " << endl; //end the programm
cin >> str;
istringstream buffer(str);
buffer >> enter;
switch (enter) {
case 1:
game();
break;
case 2:
score();
break;
case 3:
showQuizDialog();
break;
case 4:
exit = true;
break;
default:
cout << "Keine gültige Eingabe, nochmal: " << endl; //invalid input, again
void flushCin();
} //end of switch
} while (exit == false);
return enter;
}//end of menu();
If entering other things than numbers into an int value directly this might not fit into the reserved space of an int and can result in funny behaviour. So just read into a string first and then interpret it.