C++, getting a infinite loop - c++

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.

Related

Exiting the Game from the Menu is not working

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.

C++ keeps on glitching while using switch statement in while loop

I am trying to make my first text-to-play game in C++. The only problem is that the default statement in my code is making the game glitch. I am trying to use another function called exceptionHandler to deal with the default statement, but it doesn't seem to be working. Any suggestions? Here is the code:
#include <iostream>
#include <cstdlib>
using namespace std;
void space(), menu(), exceptionHandler();
int back1, back2;
int main()
{
cout << "Siddiqui Interactive presents..." << endl;
cin.get();
system("CLS");
cout << "Outland" <<endl;
cin.get();
int bob = 0;
//to loop back to main menu
while(bob < 5){
system("CLS");
cout << "Outland" <<endl;
space();
cout << "Press 1 to begin" <<endl;
cout << "Press 2 for credits" <<endl;
cout << "Press 3 to quit" <<endl;
int switch1;
cin >> switch1;
switch(switch1){
case 1:
//nothing here for now
break;
case 2:
system("CLS");
menu();
if(back1 == 1){
system("CLS");
//clears screen to loop back to the menu
}
break;
case 3:
return 0;
break;
default:
system("CLS");
exceptionHandler();
}
}
return 0;
}
void menu(){
//to create a function for the menu, saves time
cout << "This game was coded by: Shahmir Siddiqui and Ibrahim" <<endl;
cout << "Outland was designed by: Azmir Siddiqui" <<endl;
space();
cout << "Press 1 to go back" <<endl;
cin >> back1;
}
void space(){
//just saves time
cout << "" <<endl;
}
void exceptionHandler(){
//to handle exceptions or errors
system("CLS");
cout << "Invalid!" <<endl;
space();
cout << "Press 1 to go back" <<endl;
cin >> back2;
if(back2 == 1){
system("CLS");
//also clears screen to loop back to main menu
}
}
EDIT: Let's say, I typed in d instead of 1, it just keeps on fluctuating rapidly between error screen and main menu.
cin >> switch1 tries to read in an integer. If you type d (which can't be converted to an int, it doesn't "eat" the bad input so you must clear it manually.
Try adding this to your error case:
cin.clear();
cin.ignore(INT_MAX, '\n');

C++ Skipping cin statement. going into infinite loop

For some reason, it goes into the cin statement the first time but then skips it every other time in this code. After running it a few times, I realized it goes into the default case for some reason without even asking for the user input. Why?
Here's the code. It's a menu with a huge switch statement. The functions inside the switch statements aren't relevant here since it's just the overall loop.
int main()
{
Document* myDocs = new Document[10];
int docCount = 0;
bool menu = true;
int userInput = 0;
while ( menu == true )
{
//int userInput = 0;
userInput = 0;
cout << "----------------MENU----------------" << endl << endl;
cout << " --------(1) LOAD DOCUMENT (1)--------- " << endl << endl;
cout << "--------(2) OUTPUT DOCUMENT (2)--------" << endl << endl;
cout << " --------(3) ANALYZE DOCUMENT (3)-------- " << endl << endl;
cout << " ------(4) COMPARE TWO DOCUMENTS (4)------ " << endl << endl;
cout << " ----------(5) ENCRYPT (5)---------- " << endl << endl;
cout << "-----------(6) DECRYPT (6)----------" << endl << endl;
cout << "-------------(7) EXIT (7)--------------" << endl << endl;
cin >> userInput;
string docName;
string outputLoc;
switch (userInput)
{
case 1:
// Function
break;
case 2:
// Function
break;
case 3-8:
// Function
break;
default:
break;
}
Basically, I first enter the first userinput. Let's say I enter 1. Then it goes into case 1. But then after it gets out of case 1, it goes into an infinite loop that keeps displaying the menu. Shouldn't it stop at the cin statement? That's what I dont understand.
EDIT::
Case 1 is the primary one i'm worried about since I'm trying them 1 by and 1 and case 1 doesn't work.
This is the full code for case 1:
case 1: // Load Document
{
string inputLoc;
cout << "Please input the document name:" << endl;
cin >> docName;
myDocs[docCount].setName(docName);
myDocs[docCount].id = docCount;
cout << "Input Location: " << endl;
cin >> inputLoc;
myDocs[docCount].loadDocument(inputLoc);
docCount++;
break;
}
I'm starting to speculate there is something wrong with my loadDocument function.
Here is the code for that:
void Document::loadDocument(string name)
{
ifstream myFile(name);
int numOflines = 0;
string theLine;
char words;
while (myFile.get(words))
{
switch (words)
{
case '.':
numOflines++;
break;
case '?':
numOflines++;
break;
case '!':
numOflines++;
break;
}
}
lineCount = numOflines;
setLineCt(numOflines);
arr = new Line[lineCount];
myFile.close();
char theChar;
ifstream myFile2(name);
int key = 0;
if (myFile2.is_open())
{
for ( id = 0; id < lineCount; id++ )
{
while (myFile2>> noskipws>>theChar && theChar != '.' && theChar != '!' && theChar != '?') // Changed from || to &&
{
//myFile2>> noskipws >> theChar;
theLine[key] = theChar;
key++;
}
myFile2>>theChar;
arr[id].setStr(theLine);
}
}
}
Basically I'm trying to load the document and store the word count and line count from it. Is there something wrong in it?

Function Call in switch statement.

Hey guys I'm trying to work out how to call a function in my code using a switch statement. I have tried to look for many different references but no matter what nothing seems to work if somebody could please put me on the right path that would be a big help. Here's the code:
#include <iostream>
#include <string>
using namespace std;
int playGame(string word);
int main()
{
int choice;
bool menu = true;
do{
cout <<"Please select one of the following options: \n";
cout << "1: Play\n"
"2: Help\n"
"3: Config\n"
"4: Quit\n";
cout << "Enter your selection (1, 2 and 3): ";
cin >> choice;
//*****************************************************************************
// Switch menu to display the menu.
//*****************************************************************************
switch (choice)
{
case 1:
cout << "You have chosen play\n";
int playGame(string word);
break;
case 2:
cout << "You have chosen help\n";
cout << "Here is a description of the game Hangman and how it is played:\nThe word to guess is represented by a row of dashes, giving the number of letters, numbers and category. If the guessing player suggests a letter or number which occurs in the word, the other player writes it in all its correct positions";
break;
case 3:
cout << "You have chosen Quit, Goodbye.";
break;
default:
cout<< "Your selection must be between 1 and 3!\n";
}
}while(choice!=3);
getchar();
getchar();
cout << "You missed " << playGame("programming");
cout << " times to guess the word programming." << endl;
}
int playGame(string word) //returns # of misses
{
//keep track of misses
//guess is incorrect
//repeated guess of same character
//guess is correct
int misses = 0;
int exposed = 0;
string display = word;
for(int i=0; i< display.length(); i++)
display[i] ='*';
while(exposed < word.length()) {
cout << "Miss:" << misses << ":";
cout << "Enter a letter in word ";
cout << display << " : ";
char response;
cin >> response;
bool goodGuess = false;
bool duplicate = false;
for(int i=0 ; i<word.length() ; i++)
if (response == word[i])
if (display[i] == word[i]) {
cout << response << " is already in the word.\n";
duplicate = true;
break;
} else {
display[i] = word[i];
exposed++;
goodGuess = true;
}
if (duplicate)
continue;
if (!goodGuess){
misses ++;
cout << response << " is not in the word.\n";
}
}
cout << "Yes, word was " << word << "." << endl;
return misses;
}
You are not calling playGame function in switch statement,
switch (choice)
{
case 1:
cout << "You have chosen play\n";
//int playGame(string word); // this does not call playGame,
// it re-declare playGame function again
playGame("word"); // this will call playGame with word parameter
//^^^^^^^^^^^^^^^
break;
int playGame(string word);
In your switch statement might be the problem...try:
int misses = playGame(word);
You are trying to return the number of misses from your playGame method so you have to put the return data inside a variable.

Menu driven project

The instructor want us to write a program that can re displays the menu only when the user wants to restart a selection and add an option to continue with another selection.
The problem I have is when the user select a number from 1 to 4 and complete the selection, the program will ask the user if the user want to continue with another selection and when the user says no, the program still ask to select a number without ending program.
here is my code that I've written so far:
#include<iostream>
using namespace std;
int sp;
int speed = 0;
int M, K, c, x;
const int MINspeed = 10;
const int MAXspeed = 40;
int GetSpeed();
int GetMinSpeed();
int GetMaxSpeed();
int CheckContinue();
int selection;
int GetSpeed()
{
char c;
while(true)
{
cout << "\nDo you want the speed in mph or km/h? \n"
<< "\nEnter M or K followed by Enter: " << endl;
cin >> c;
if( (c != 'M')&& (c != 'K'))
{
cout << "Incorrect Selection. Try Again! \n\n";
break;
}
if ( c == 'M')
{
cout << "\nSpeed in mph: " << speed << endl;
return speed;
}
else if(c == 'K')
{
double toKmPerHour = 1.61;
double speedInKmPerHour = speed * toKmPerHour;
cout << "\nSpeed in km/h:" << speedInKmPerHour << endl;
break;
}
CheckContinue();
}
return 0;
}
int GetMinSpeed()
{
cout << "MIN speed = " << MINspeed << endl;
CheckContinue();
return 0;
}
int GetMaxSpeed()
{
cout << "MAX speed = " << MAXspeed << endl;
CheckContinue();
return 0;
}
/*int SetSpeed(int sp)
{
cout << "The Set Speed is " << sp << endl;
return 0;
}
*/
void SetSpeed()
{
cout << "Input your speed: ";
cin >> speed;
CheckContinue();
}
int CheckContinue(void)
{
char x;
while(true)
{
cout << "\nDo you want to continue with another selection? \n"
<< "\nEnter Y or N followed by Enter: " << endl;
cin >> x;
if ( x == 'Y')
{
int selection;
cout << "Selection Menu" << endl;
cout << "--------------" << endl;
cout << "\n1. Set Speed" << endl;
cout << "2. Get Speed" << endl;
cout << "3. Get MAX Speed" << endl;
cout << "4. Get MIN Speed" << endl;
cout << "5. Exit" << endl;
cout << "\nYour selection :" <<endl;
cin >> selection;
switch(selection)
{
case 1:
SetSpeed();
break;
case 2:
GetSpeed();
break;
case 3:
GetMaxSpeed();
break;
case 4:
GetMinSpeed();
break;
case 5:
cout << "Good Bye" << endl;
break;
}
}
else if(x == 'N')
{
break;
}
}
return 0;
}
/*
In this menu function, it will ask the user to input the selection, ranging from 1 to 5.
If the user puts a number that is not between 1 to 5 or letters, then the program will
ask the user to input a valid selection.
*/
void menu()
{
int selection;
cout << "Selection Menu" << endl;
cout << "--------------" << endl;
cout << "\n1. Set Speed" << endl;
cout << "2. Get Speed" << endl;
cout << "3. Get MAX Speed" << endl;
cout << "4. Get MIN Speed" << endl;
cout << "5. Exit" << endl;
int bye = 0;
while(1)
{
cout << "\nYour selection :" <<endl;
cin >> selection;
bye = 0;
if((selection <= 5)&&(selection >= 1))
{
switch(selection)
{
case 1:
SetSpeed();
break;
case 2:
GetSpeed();
break;
case 3:
GetMaxSpeed();
break;
case 4:
GetMinSpeed();
break;
case 5:
cout << "Good Bye" << endl;
bye = -1;
break;
}
}
else
{
cout << "\nPlease input valid selection: " << endl;
cin >> selection;
switch(selection)
{
case 1:
SetSpeed();
break;
case 2:
GetSpeed();
break;
case 3:
GetMaxSpeed();
break;
case 4:
GetMinSpeed();
break;
case 5:
cout << "Good Bye" << endl;
bye = -1;
break;
}
}
if(bye == -1)
{
break;
}
}
}
int main()
{
menu();
return 0;
}//end of main function
This might serve your purpose. Call ask() as per your requirement if it didn't suit you.
#include <iostream>
#include <stdlib.h>
using namespace std;
char * title;
int a , b;
void menu();
void print(const char *c , int res )
{
cout<<"\n\n\n\n\nThe "<<c<<" of "<<a<<" and "<<b<<" is : " <<res<<endl;
}
void add()
{
print("Addition" , (a+b));
}
void sub()
{
print("subtraction" , (a-b));
}
void mul()
{
print("Multiplication" , (a*b));
}
void div()
{
print("Division" , (a/b));
}
void ask()
{
bool call_menu;
char ch;
cout<<"\n\n\n\n\n\n DO you Want to Continue? Y - N: ";
cin>>ch;
if(ch=='Y' || ch=='y')
{
call_menu= true;
}
else
{
if(ch=='N' || ch == 'n')
{
call_menu= false;
}
else
{
cin.clear();
ask();
}
}
if(call_menu)
{
system("clear"); // change this to system("cls") if on windows
menu();
}
else
{
system("clear"); // change this to system("cls") if on windows
cout<<"\n\n\n\n\n\n\n\t\t\tHave a Nice Day ! \n\n\n"<<endl;
}
}
void input(int *first , int *second)
{
system("clear"); // change this to system("cls") if on windows
cout<<"\n\n\n\t\t\t\t Calculator \n\n\n\n"<<endl;
cout<<"Enter the First Number : ";
cin>>(*first);
cout<<"\nEnter the Second Number :";
cin>>(*second);
}
void menu()
{
int ch;
cout<<"\n\n\n\t\t\t\t Calculator \n\n\n\n"<<endl;
cout<<"\n\n\t\t\t1 . Addition"<<endl;
cout<<"\n\n\t\t\t2 . Subtract"<<endl;
cout<<"\n\n\t\t\t3 . Multiply"<<endl;
cout<<"\n\n\t\t\t4 . Division"<<endl;
cout<<"\n\n\t\t\t5 . Exit" <<endl;
cout<<"\n\n\n\n Enter Your Choice : ";
cin>>ch;
if(ch >=1 && ch <5){
input(&a , &b);
}
switch(ch)
{
case 1:
add();
ask();
break;
case 2:
sub();
ask();
break;
case 3:
mul();
ask();
break;
case 4:
div();
ask();
break;
case 5:
exit(0);
break;
default:
system("clear"); // change this to system("cls") if on windows
cin.clear();
cin.ignore();
menu();
break;
}
}
int main(int argc, char **argv)
{
menu();
return 0;
}
Modify it as per your requirement.
There are several problems with the code in your question. The big problem is there is a lot of redundant code that can be easily eliminated by a few minor adjustments. You have both the menu printing and code to act on selections in several places. This is going to make managing the continue process a lot more difficult. By eliminating the redundant code and adjusting the logic in main and and menu you can not only reduce the complexity but make it far easier to manage.
For instance menu can be changed to remove the while loop and return a boolean value to indicate if the user wants to exit. This will allow you to select an option, act on it, then return letting other portions of the program handle asking the user if they want to continue.
The example below is a modification of your original code. It only addresses the logic for asking the user to continue and eliminates the redundant menu code. You should review the entire code and make additional adjustments as necessary.
#include <iostream>
#include <string>
using namespace std;
int sp;
int speed = 0;
int M, K, c, x;
const int MINspeed = 10;
const int MAXspeed = 40;
int GetSpeed()
{
char c;
while(true)
{
cout << "\nDo you want the speed in mph or km/h? \n"
<< "\nEnter M or K followed by Enter: " << flush;
cin >> c;
if( (c != 'M')&& (c != 'K'))
{
cout << "Incorrect Selection. Try Again! \n\n" << flush;
continue;
}
if ( c == 'M')
{
cout << "\nSpeed in mph: " << speed << endl;
return speed;
}
else if(c == 'K')
{
double toKmPerHour = 1.61;
double speedInKmPerHour = speed * toKmPerHour;
cout << "\nSpeed in km/h:" << speedInKmPerHour << endl;
return speed;
}
}
return 0;
}
int GetMinSpeed()
{
cout << "MIN speed = " << MINspeed << endl;
return 0;
}
int GetMaxSpeed()
{
cout << "MAX speed = " << MAXspeed << endl;
return 0;
}
void SetSpeed()
{
cout << "Input your speed: ";
cin >> speed;
}
/*
In this menu function, it will ask the user to input the selection, ranging from 1 to 5.
If the user puts a number that is not between 1 to 5 or letters, then the program will
ask the user to input a valid selection.
returns false if the user has selected the exit option
returns true for all other options
*/
bool menu()
{
cout << "Selection Menu" << endl;
cout << "--------------" << endl;
cout << "\n1. Set Speed" << endl;
cout << "2. Get Speed" << endl;
cout << "3. Get MAX Speed" << endl;
cout << "4. Get MIN Speed" << endl;
cout << "5. Exit" << endl;
int selection;
cout << "\nYour selection :" <<endl;
cin >> selection;
switch(selection)
{
case 1:
SetSpeed();
break;
case 2:
GetSpeed();
break;
case 3:
GetMaxSpeed();
break;
case 4:
GetMinSpeed();
break;
case 5:
cout << "Good Bye" << endl;
return false;
break;
default:
cout << "\nPlease input valid selection: " << endl;
}
return true;
}
int main()
{
for(bool process = true; process;)
{
process = menu();
if(process)
{
for(bool valid = false; !valid;)
{
cout << "\nDo you want to enter another selection? (Yes/No) " << flush;
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
string line;
getline(cin, line);
if(line == "No")
{
valid = true;
process = false;
}
else if(line == "Yes")
{
valid = true;
}
else
{
cout << "\nInvalid input\n\n" << flush;
}
}
}
}
return 0;
}//end of main function