-
switch problems
im working on a texted adventure where the user can walk around a map to solve puzzles. im using a switch to move. if a player can only go east, west or south from the room they are in i have a default for if they try to go north. my problem is that when they go into the defualt it kicks them out of the program. i tried putting the switch into a while loop that should repeat until they enter a valid answer but it goes into infinite loop if they go into the default. i dont understand why its doing this. is my loop wrong or am i going about it the wrong way? my switch with the loop is below. the letters represent the direction they are going.
Code:
int x=0;
while (x!=1)
{
switch(direction)
{
case 'e':
case 'E':
x=1;
room3();
break;
case 's':
case 'S':
x=1;
room5();
break;
case 'w':
case 'W':
x=1;
room1();
break;
default:
x=0;
cout << "not a choice\n";
}
}
-
I think you just need a break statement in the default case, and if you're using Dev-C++, you'll need to use cin.get() to pause the program before it exits. Or use:
Code:
while (char a=getchar() !='\n');
Another problem programmers run into all the time is lines of code that don't execute because there's already a new line stored in the buffer, which can be cleared using cin.ignore();
-
You don't need a break statement in the default case. It breaks anyway.
-
Can I see more of your code? The switch ... case LOOKS ok.
-
The only thing wrong with the switch is in the default case. You don't need to set x to 0 if it's already 0. Unless, of course, the rest of your code modifys x. :)
-
got it
thanks for all the input but i figured it out. i didnt have the cin inside the while. thanks again for being willing to help, i may have more questions. im planning on posting the final code for anyone thats interested in a beginners text adventure. off to do more coding