Having problems with switch cases..

Im writing a simple little rock paper scissors game and i have ran into a problem.

I'm using a switch statement on the variable decided by cin. It is the variable you set when you type in rock paper or scissors.

So far i am only able to get it to work if i only use a single letter for the case. For example. r for rock. p for paper. s for scissors. I would like to know how to set it so that the cases inside the switch will be "case "rock":". Or something along the likes of it.. a sample of my code.


1
2
cout << "Input: ";
		cin >> handsign;


1
2
3
switch(handsign)
			{
			case 'r':


EDIT: IF it matters.. im using Visual C++ 2005.

Last edited on
You can't, you can only switch on integral types. You'll have to use if statements.
so to use the if in the same spot.

i dont think

if(handsign == "rock")

would work?

do i have to use strings..?
You can use a switch statement on char! The following code works fine:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
int main()
{
	char c = ' ';

	do
	{
		std::cout << "\na, b, c - e to exit\n";
		std::cout << "Input a char: ";
		std::cin >> c;
	
		switch( c )
		{
			case 'a':
				std::cout << "you entered " << c << '\n';
				break;

			case 'b':
				std::cout << "you entered " << c << '\n';
				break;

			case 'c':
				std::cout << "you entered " << c << '\n';
				break;

			case 'e':
				return 0;

			default:
				std::cout << "a, b or c were not entered.\n";
		}
	}while( true );


	return 0;
}


If you want to make the user enter the whole word and then do a check, you could do the following:

1
2
3
4
5
6
7
8
9
    char handsign[10];

    std::cout << "Please enter 'rock', 'paper', 'scissors': ";
    std::cin >> handsign;

    switch( handsign[ 0 ] )    //check the first letter of the array, 'r', 'p' or 's'
    {
        ....code....
    }
Last edited on
If you change handsign to be a string then you can use
 
if(handsign == "rock")
if handsign is a char array, use:
 
if (strcmp(handsign, "rock") == 0)
Thanks Guys. Ended up using lynx's idea. Now to work in a score...
To be honest, I would have used what kbw said.
if( handsign == "rock" )
i went through and added a score system. Converted it to kbw's suggestion. Works out easier to work with for other things. Finally finished my first proper c++ game. Thanks.
Topic archived. No new replies allowed.