2

I am trying to code a little game-like adventure program, and I need if else statements in it for it to work correctly. However, whenever I run this if else statement, it does not output what I want.

#include <iostream>

using namespace std;

int main()
{
    while(true)
    {
        cout << endl << "What will you do?: ";
        string input;
        cin >> input;
        if (input == "Nothing" || input == "nothing")
            {
                cout << "Why would you do nothing?" << endl;
            }
            else if (input == "Look North" || input == "Look north" || input == "look North" || input == "look north")
            {
                cout << "You look north. There is nothing north." << endl;
            }
    }
}

What I expect it to output would be this:

What will you do?: nothing
Why would you do nothing?

What will you do?: look north
You look north. There is nothing north.

What will you do?:

But instead of getting that when I put those as an input, I get this:

What will you do?: nothing
Why would you do nothing?

What will you do?: look north

What will you do?:
What will you do?:

I would like some help on resolving this issue, as I cannot find an answer to why this would be happening.

  • 1
    Debugging tip: Output the thing you've just input to verify that it is what you think it is. – molbdnilo Dec 21 '15 at 15:48
  • Or run through a debugger and examine the input variables. Not much different but I find it a bit cleaner. – Edward Strange Dec 21 '15 at 15:51
  • 1
    Game design tip: as soon as you will have about 10 locations linked to each others, you will start to hate everything. Think about making locations and links to other locations data-driven – Revolver_Ocelot Dec 21 '15 at 15:51
  • 1
    Please *transform* your strings into all lowercase or all uppercase before comparing. This reduces the need to compare for "nOrth", "NoRtH", "North", "north" and all other combinations. – Thomas Matthews Dec 21 '15 at 15:55

3 Answers3

5
cin >> input;

does not read whitespaces. You need to use std::getline.

getline(cin, input);
R Sahu
  • 204,454
  • 14
  • 159
  • 270
0

Because when you input "Look north" using cin>>input; only "Look" is saved into the input variable ..

Ankur Jyoti Phukan
  • 785
  • 3
  • 12
  • 20
0

The problem is withcin statement as it does not handle white spaces, try what is posted here. Also, you will find helpfull the tolower() function, to normalize your inputs.

Community
  • 1
  • 1
ASMateus
  • 71
  • 5