简体   繁体   中英

If else if, code only resolves to else condition

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.

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM