My first program in C++ is a command line survival game. I have a switch statement in a while loop, but it always goes through once and runs the default choice before getting the users input. Here's the relevant code:
int menu() {
while (true) {
char choice = getChoice();
switch(choice) {
case 'p':
{
system("clear");
Arena arena(player, difficulty);
arena.play();
}
break;
case 'u':
{
system("clear");
player.save();
player.init();
}
break;
case 'd':
{
system("clear");
changeDifficulty();
}
break;
case 'q':
{
system("clear");
return 0; // return menu(); in main()
}
default:
{
system("clear");
cout << nInvalid option! Press a key to choose: p, u, s, or q\n\n";
break;
}
}
}
}
getChoice Function
char getChoice() {
cout << " Main Menu\n";
cout << "---------------------\n";
cout << "p - play game" << endl;
cout << "u - change user" << endl;
cout << "d - change difficulty" << endl;
cout << "q - quit\n" << endl;
char choice = getchar();
return choice;
}
Everything works fine after it goes through once and runs the code from the default option. Here's what I get every time the program re-enters this loop:
Invalid option! Press a key to choose: p, u, s, or q
Main Menu
---------------------
p - play game
u - change user
d - change difficulty
q - quit
Thanks for any help in advance!
Aucun commentaire:
Enregistrer un commentaire