-1

I am Making a Simple game and I am having a problem with the if statement. I have the formatting of the statement right but there is no output

I am trying to output a cout text and then ask the user to input another action

I have tried isolating the Problem by trying to print out the string which I used to record the input for the action

#include <iostream>
#include <iomanip>
#include <conio.h>
#include <string>
using namespace std;

int main() {
    int charisma1 = 50;
    string action, choice;

    cout << "Hello There!\n";

    cout << "\nBefore we start you need to learn the basics commands of theis game\n";
    cout << "\nGo North -- To Move North\n";
    cout << "Go South -- To Move South\n";
    cout << "Go West -- To Move West\n";
    cout << "Go East-- To Move East\n";

    cout << "\nIF YOU WANT TO SKIP THE TUTORIAL THEN TYPE \"Yes\": ";
    cin >> choice;
    if (choice != "yes") {
        cout << "\nAttack -- To Attack your enemy (You will have to however have a weapon equiped)\n";
    }

    cout << "\nEast of House\n";

    cout << "\nYou are standing outside in a clearing west of a east house with a boarded front door\n";
    _getch();
    cout << "You see a mailbox there\n";
    cin >> action;
    if (action == "open mailbox"){
        cout << "You see a letter inside\n";
    }

    return 0;
}

you see a mailbox Input: open mailbox you see a letter inside Input: read letter Letter goes here

πάντα ῥεῖ
  • 1
  • 13
  • 116
  • 190

2 Answers2

2

When you use

cin >> action;
if (action == "open mailbox"){
    cout << "You see a letter inside\n";
}

The conditional in the if is bound to be false. The line to read into action will stop reading when it encounters a whitespace character. If you want to read whitespace characters into action, you can use std::getline.

std::getline(cin, action);

However, that will lead to another problem. The previous call to read from cin,

cin >> choice;

is going to leave the newline character in the stream. Before you can use std::getline, make sure you read and discard the newline character (and anything else before the newline character). You can use cin.ingore for that.

cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
std::getline(cin, action);

Add

#include <limits>

to be able to use std::numeric_limits.

R Sahu
  • 204,454
  • 14
  • 159
  • 270
0

in C++, cin is whitespace-delimited. That means once the function encounters a space, tab, newline, etc, it stops reading characters in. To read a full line (i.e. delimit on Enter) use the getline() function instead and pass it the destination string.

Adam S.
  • 21
  • 3