Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

If else if, code only resolves to else condition

Tags:

c++

I'm trying to make a pretty basic text adventure to test my rudimentary skills. The basic movement prompts user input, and if it matches certain strings, changes their coordinates. I know, it's stupid. But the if, else if, else for matching their response always returns else, even if you enter one of the matching strings.

string action;
string west = "go west";
string east = "go east";
string north = "go north";
string south = "go south";
string prompt = "Don't just stand around with your dagger in your ass! Do something! ";

//i wrote a bunch of setup story here, it's irrelevant text output

int vertical = 25;
int horizon = 20;

//action begins
start:
{
cout << "What do you do?" << endl;
cin >> action;

if (action == south)
{
    vertical = vertical - 5;
    goto descriptions;
}
else if (action == east)
{
    horizon = horizon + 5;
    goto descriptions;
}
else if (action == west)
{
    horizon = horizon - 5;
    goto descriptions;
}
else if (action == north)
{
    vertical = vertical + 5;
    goto descriptions;
}
else
{
    cout << prompt << "(Try typing \"go\" followed by a direction)" << endl;
    goto start;
}

description:
//i put a bunch of if, else if, else stuff about coordinates describing the area down here.

When I type "go east" or "go north", it prints the prompt string about daggers and asses, which should only print if i type something else. What am I doing wrong? To clarify, I'm using Xcode on OS X 10.10.3.

like image 657
Cameron Avatar asked Dec 11 '22 22:12

Cameron


2 Answers

Value of action read from input would only be "go", it stops on first whitespace character. See behavior of operator>>.

like image 185
Werkov Avatar answered Dec 27 '22 15:12

Werkov


cin >> string reads one word at a time, not one line. So if the input contains "go north", the first >> will read "go" and the second "north", neither of which are equal to "go north".

Use getline to read a whole line.

like image 29
sepp2k Avatar answered Dec 27 '22 14:12

sepp2k