How can I make a loop in switch?

Hello.
What i'm required to do is to create a menu, call a function, and ask the user if he wants to continue.
In this case the user will play a slot machine.

This is the code that I have for the function:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
void slotmachine(char spin);
void slotmachine(char spin)
{
	int slot1, slot2, slot3;

	srand(time(0));
	
	slot1 = rand() % 7;
	slot2 = rand() % 7;
	slot3 = rand() % 7;

	cout << "You Got: " << endl;
	cout << slot1 << " " << slot2 << " " << slot3 << endl << endl;

	if (slot1 == slot2 == slot3)
	{
		cout << "WINNER\n" << endl;
	}
	else
		cout << "LOSER\n" << endl;


}



And this is the code that I have for the case:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
case 4:
			cout << "Type SPIN to start" << endl;
			cin >> spin;
			again = 0;
			do
			 {
				slotmachine(spin);
				cout << "would you like to play again? Press 1 to exit" << endl;
				cin >> again;
			}	
			 while (again != 0);

			system("pause");
			break;



the thing is that no matter what I input after the question to play again, the function keeps running.
Also, sometimes it says winner even though numbers aren't matching.

What could be wrong with the code?
Yes, you will just need to wrap the case in braces

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
case 4:
{   // <---
			cout << "Type SPIN to start" << endl;
			cin >> spin;
			again = 0;
			do
			 {
				slotmachine(spin);
				cout << "would you like to play again? Press 1 to exit" << endl;
				cin >> again;
			}	
			 while (again != 0);

			system("pause");
			break;
} // <--- 
1
2
//if (slot1 == slot2 == slot3)
if (slot1 == slot2 and slot1 == slot3)


1
2
cout << "Type SPIN to start" << endl;
cin >> spin;
by looking at the unneeded parameter in `slotmachine()' I deduce that `spin' is a char
A char can only hold one character, if you are inputting "SPIN" then you are passing "PIN" when doing cin >> again;
what is the type of 'again'?
if it is a character, this won't work because it is rather difficult to enter the null character (0) from the keyboard.

you should either check '0' or 'y' or 'Y' or something like that if it is a character.
Last edited on
the thing is that no matter what I input after the question to play again, the function keeps running.


"Press 1 to exit"

but the loop will only exit if again==0

while (again != 0);

You need to make these the same as each other. And as jonnin pointed out, "again" should be some kind of int.
Last edited on
Thank You ne555.

I forgot that char only take 1 character. That's why it displayed three times the same number (i guess).

I switched spin for int, and now the loop is closing.


Thank you everyone for your responses.
Topic archived. No new replies allowed.