Hi,i'm relatively new to programming and decided to try writing a small text adventure thing to test out switch statements. However when i reach an ending such as you have been eaten by a gru, the program also outputs you are killed and you fall off the edge of the world.
I was just wondering if there was any solution to this or whether i just cant use switch statements for this kind of thing?
Any help would be greatly appreciated, please and thank you.
#include <iostream>
usingnamespace std;
int main()
{
char x, y, z;
cout << "You are in a forest, the path leads to the north and south. Which direction will you go?";
cin >> x;
switch(x) {
case'n':
cout << "You head north and eventually come to a small house. Do you wish to enter?";
cin >> y;
switch (y) {
case'y':
cout << "You head inside and see a dusty old ladder leading up to the attic. Do you wish to climb the ladder?";
cin >> z;
switch (z) {
case'y':
cout << "it is dark. You have been eaten by a gru.";
break;
case'n':
cout << "you are boring and live out the rest of your days in peace...";
break;
default:
cout << "You stand still and are hit by a falling star, Mission failed.";
}
case'n':
cout << "you are killed";
}
case's':
cout << "you fall off the edge of the world.";
}
return 0;
}
case 'n' and case 's' are missing break; - also those should be above default because default is run if non of the above cases are met. Plus you seem to have two case 'n'
I tried adding the breaks but it still didn't work, also i was under the impression that it shouldn't matter that there are two cases with the same value as they are in separate switch statements?
case 'n' needs a break otherwise it will continue running the code of case 's'.
case 's' does not strictly need a break because it's the last case in the switch so the switch ends anyway, but putting a break here doesn't hurt and eliminate the risk of forgetting to adding it later in case you add another case.
also those should be above default because default is run if non of the above cases are met. Plus you seem to have two case 'n'
He actually has 3 switch statements in his code and the default is part of the innermost switch. The order doesn't matter though. The default can be first, or last, it doesn't matter.
I tried adding the breaks but it still didn't work
You also need to add break to some of the cases in the inner switches. If you are not sure which ones, just add it to all of them.
I know i am probably making a very stupid mistake here but i have tried everything suggested, adding breaks to all the cases, i have removed the default as it wasn't really needed in the first place and have checked all the parenthesis to make sure i haven't forgotten to end a switch statement, and it is still executing the last two cases when it should be ending after one of the cases in switch z executes.
All good now, i knew it would be a stupid mistake, hadn't put the breaks in the right place for the first case y and the first case n. Thanks for the help.