Total amount of games not displaying at end of switch loop cycle - c++

so for one of my projects I am supposed to give the user multiple games to choose from, which can be played however many times they would like. As soon as they exit, the program should display the total amount of games played.
I have the code for the games done, I'm just working on the menu separately. For some reason when I call for the total at the end, it doesn't output anything. Not even the initial value that I place for the integer.
Any help is much appreciated!
#include <iostream>
using namespace std;
int main() {
int totalGames = 0;
while (true) {
int gameChoice;
cout << "Which game would you like to play?\n\n";
cin >> gameChoice;
switch (gameChoice)
{
case 1 :
cout << "You chose option 1";
totalGames++;
break;
case 2 :
cout << "You chose option 2";
totalGames++;
break;
case 3 :
cout << "You chose option 3";
totalGames++;
break;
case 4 :
return false;
break;
default:
cout << "Invalid Option";
break;
}
}
cout << "Total games: " << totalGames << endl;
return 0;
}

As already suggested in comment and #MichaelVeksler, case 4 exits the program and thus it doesn't output anything.
For instance, you can output it terminating while-loop using a boolean flag as follows:
DEMO
bool doContinue = true; // flag
while (doContinue)
{
int gameChoice;
cout << "Which game would you like to play?\n\n";
cin >> gameChoice;
switch (gameChoice)
{
case 1 :
cout << "You chose option 1";
totalGames++;
break;
case 2 :
cout << "You chose option 2";
totalGames++;
break;
case 3 :
cout << "You chose option 3";
totalGames++;
break;
case 4 :
doContinue = false;
break;
default:
cout << "Invalid Option";
break;
}
}

The issue is with:
case 4 :
return false;
Which exits the program, before reaching the printing statement.

Related

Is there a way to input different value for the same data when the same function is called multiple times?

I'm creating a student data management program in C++ and the function to insert examination marks is buggy.
The code given below is enough to recreate the buggy part of the program.
I have tried to increase the size of sub[] to 16
I have tried to insert data one after the other instead of a loop
None of the above seem to solve the problem
Menu function:
char ch;
main_menu:
clrscr();
cout << "Press the key for your choice:\n";
cout << "D -> Edit details\n";
cout << "R -> Get result\n";
cout << "I -> Insert marks\n";
cout << "E -> Exit Program";
choice:
ch = getch();
switch(ch)
{
case 'd':
//edit_nam(); Ignore this one
goto main_menu;
break;
case 'i':
ins_mar();
goto main_menu;
break;
case 'r':
//get_res(); This one is not related to the problem
goto main_menu;
break;
case 'e':
break;
default:
goto choice;
}
Insert marks function:
for(int i = 0; i < 6; i++)
{
clrscr();
cout << "Enter details of subject:" << i + 1;
cout << "\nSubject name:";
cout << "\nMarks:";
gotoxy(14, 1);
cin.getline(student.marks[i].sub, 8);
gotoxy(7,2);
cin >> student.marks[i].mark;
(i != 5) ? cout << "\nPress any key to continue..." : cout << "\nPress any key to return to menu...";
getch();
}
Student structure:
struct stu
{
char name[20];
int ID;
int cls;
mar marks[6];
};
Marks structure:
struct mar
{
char sub[8];
float mark;
}
If the code was working fine, then it would ask the user to enter the marks for all six subjects, every time the function is called in one run.
However, It is not so. In the first time of function call, everything happens in the correct manner, but it does not ask for subject name after first subject in any of the other runs.

Can't get it back to loop. C++

I'm trying to get it back to loop if they enter anything from the choices. everytime I enter 4, it just ends. and if I pick the right one it also ends. Is there anyway I can get it to ask user to input the right one?
void towsoncourse ()
{
cout << "Enter Course: 1 is COSC,2 is ENGL,3 is MATH" << endl;
int course;
bool finish;
bool finishcourse = true;
cin >> course;
while (finishcourse != true)
{
cout << "Enter correct number for course" << endl;
if (course == 1 || course == 2 | course == 3)
{
finish = true;
}
else
{
cout<< "Error: Enter number corresponding to course." << endl;
}
}
switch (course)
{
case 1:
cout << "COSC" << endl;
break;
case 2:
cout << "ENGL" << endl;
break;
case 3:
cout << "MATH" << endl;
break;
default:
cout << "Error: Enter number corresponding to course" << endl;
}
}
int main ()
{
towsoncourse ();
return 0;
}
Not a complete answer, but rather a guide to point the way.
You want to keep reading an input until it is one of 3 possible values. So a good place to read and test the input would be inside a loop, exiting only when the test conditions are met.
while loops test continue criteria before each execution. do loops test continue criteria after each execution. In you case it is necessary to execute at least once.
There were some issues with the code.
1) while (finishcourse != true) condition was wrong. It should be while (finishcourse == true).
2) finish = true; assignment was wrong. It should have been finishcourse = false;
3) cin >> course; should be taken inside the loop. Because if you place it outside, it will lead to infinite loop in case of incorrect entry.
So, Just to ensure readability, I have rewritten the code. I have assumed that it gets back to the loop in case of incorrect entry and in case of correct entry, it terminates.
#include <iostream>
using namespace std;
void towsoncourse ()
{
bool finishcourse = true;
while (finishcourse == true)
{
int course;
cout << "Enter Course: 1 is COSC,2 is ENGL,3 is MATH" << endl;
cin >> course;
switch (course)
{
case 1:
cout << "COSC" << endl;
finishcourse = false;
break;
case 2:
cout << "ENGL" << endl;
finishcourse = false;
break;
case 3:
cout << "MATH" << endl;
finishcourse = false;
break;
default:
cout << "Error: Enter number corresponding to course." << endl;
}
}
}
int main ()
{
towsoncourse ();
return 0;
}

Unable to understand the flow of the program

I am unable to understand as to why the switch block is not executed. I am trying to generate random numbers between 0 and 2 using rand() within comp_in() function. I return the number to the main function. Within the main function, I am trying to associate a char to each letter generated. The switch statement is not executed at all. Please help!
#include<iostream>
using namespace std;
int comp_in();
int main()
{
char h;
h = human_in();
int c = comp_in();
cout << "c is" << c << endl;
switch(c)
{
case '0' : cout << "Computer's choice is : 'R'" << endl;
break;
case '1' : cout << "Computer's choice is : 'P'" << endl;
break;
case '2' : cout << "Computer's choice is : 'S'" << endl;
break;
}
}
int comp_in()
{
int s;
for(int i=0; i<4; i++)
{
s=rand()%3;
}
cout << "s is : " << s << endl;
return s;
}
Output:-
s is : 1
c is1
The problem is that your comp_in function returns numbers, but your switch is comparing its result to characters. Simply remove the single quotes from each case, making them numbers, and it'll work:
switch(c)
{
case 0 : cout << "Computer's choice is : 'R'" << endl;
break;
case 1 : cout << "Computer's choice is : 'P'" << endl;
break;
case 2 : cout << "Computer's choice is : 'S'" << endl;
break;
default: cout << "Computer made a really strange choice: " << c << endl;
break;
}
Do note that at some point in the future, you might want to compare the human input with the computer input. Since your human_in function returns a character, you're going to have to convert it by using a function like atoi.
You can detect bugs like these more quickly if you output some sort of debug message in a default case, which I've also included in the code sample above.

How can I give the user choice again in the following small c++ code?

#include <iostream>
using namespace std;
void playgame ()
{}
void loadgame ()
{}
void playmultiplayer ()
{}
int main ()
{
int input;
cout << "1. Play game\n";
cout << "2. Load game\n";
cout << "3. Play multiplayer\n";
cout << "4. Exit\n";
cout << "Selection: ";
cin >> input;
switch ( input )
{
case 1: // Note the colon after each case, not a semicolon
playgame();
break;
case 2:
loadgame();
break;
case 3:
playmultiplayer();
break;
case 4:
cout << "Thank you for playing!\n";
break;
default: // Note the colon for default, not a semicolon
cout << "Error, bad input, quitting\n";
break;
}
}
This code is from the book I am currently studying, "jumping into c++" to describle the working of switch.
the author said " one issue you might notice is that the user gets only a single choice before the program exists. We can use while loop to around the switch block to solve the issue".
my question is - How can we use while loop to solve the issue? I tried a lot but am unable to do it.
Thanks.
You can do it like this using a do { ... } while() loop construct.
do {
if(cin >> input) {
// your switch
switch(input) {
case 1:
break; //
// so on
case 4:
cout << "Thank You!" << std::endl;
break;
}
} else {
// io error
break;
}
} while (input != 4);
I'd like to point out that your book probably sucks. Reading from a stream without checking the return value is just plain bad code. My code checks if the formatted input function actually extract output.
You can put the code in a do while loop and instead of exiting in the case 4,u can have the exit condition defined in the while condition.This way the user gets the option until he chooses 4
I guess the book will show examples of loops in the next chapter or so.
To answer your question: (as endless loop)
while(true)
{
//your code starting with cout ... ending with the closing } othe switch
}
#include <iostream>
using namespace std;
void playgame ()
{}
void loadgame ()
{}
void playmultiplayer ()
{}
int main ()
{
int input;
while(1)
{
cout << "1. Play game\n";
cout << "2. Load game\n";
cout << "3. Play multiplayer\n";
cout << "4. Exit\n";
cout << "Selection: ";
cin >> input;
switch ( input )
{
case 1: // Note the colon after each case, not a semicolon
playgame();
break;
case 2:
loadgame();
break;
case 3:
playmultiplayer();
break;
case 4:
cout << "Thank you for playing!\n";
exit(1);
break;
default: // Note the colon for default, not a semicolon
cout << "Error, bad input, quitting\n";
break;
}
}
}
You could wrap everything inside main() inside the following:
bool quit = false;
while(!quit)
{
//your code
}
And for cases 4 and 5, add
quit = true;
before break;

For loop not working correctly

I need the for loop to execute 4 times in the program and then to exit at the fourth time and give the total of the results.
It should not count X as a spoilt vote
The three totals and the number of spoilt votes are initialised to 0.
Now a for loop follows, going from 1 to the number of voting stations.
Inside this loop is a while loop. A prompting message appears on the screen, asking the
voter for which candidate he or she wants to vote. The choice of the voter is then input.
Inside the while loop is a switch statement to increment the correct total. The default
option is used to count the number of spoilt votes.
The while loop is exited when X is entered for the choice.
When the for loop is exited, the three totals and the number of spoilt votes are displayed.
Here is my code
int main()
{
const int NR_VOTING_STATIONS = 4;
int votesForA, votesForB, votesForC, spoiltVotes;
char vote;
// initialise totals
votesForA = 0;
votesForB = 0;
votesForC = 0;
spoiltVotes = 0;
// LOOP of INTEREST START
//loop over the voting stations
for ( int i = 1; i <= NR_VOTING_STATIONS; i++)
{
//loop over voters
while (vote != 'X')
{
cout << "Vote for candidate A, B or C : " << endl;
cin >> vote;
switch(vote)
{
case 'A':
votesForA++;
break;
case 'B':
votesForB++;
break;
case 'C':
votesForC++;
break;
default:
spoiltVotes++;
}
}
}
// LOOP of INTEREST END
//display results
cout << endl << endl;
cout << "Total candidate A : " << votesForA << endl;
cout << "Total candidate B : " << votesForB << endl;
cout << "Total candidate C : " << votesForC << endl;
cout << "Total spoilt votes: " << spoiltVotes << endl;
system("pause");
return 0;
}
Thanks
just add in the switch:
case 'X':
break;
because the while condition will not be executed until the next round.
If the question is
It should not count X as a spoilt vote
The answer would be to add a case:
case 'X':
break;
Also, be careful to initialize vote first, or use do { } while() rather than while { }
If you need the for loop to execute four times why not just surround it in another for loop?
In the while loop you should check whether the Voters in that polling sttion are still available. Since you are neutral at the input 'X', you should add it as one of the cases in the switch.
Your new while loop should look like:
Voters_Still_Present = 1;
while (Voters_Still_Present)
{
cout << "Vote for candidate A, B or C : " << endl;
cin >> vote;
switch(vote)
{
case 'A':
votesForA++;
break;
case 'B':
votesForB++;
break;
case 'C':
votesForC++;
break;
case 'X':
//do nothing
break;
default:
spoiltVotes++;
}
/* Here, find out if voters are still available in the present station.
If yes, Voters_Still_Present = 1; else Voters_Still_Present = 0;
*/
}