if语句不输出任何内容

时间:2019-07-01 19:06:04

标签: c++

我正在制作一个简单的游戏,并且if语句有问题。我的语句格式正确,但是没有输出

我正在尝试输出提示文字,然后要求用户输入其他操作

我试图通过尝试打印出我用来记录动作输入的字符串来隔离问题

#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;
}

您看到一个邮箱 输入:打开邮箱 你里面看到一封信 输入:已读信 信在这里

2 个答案:

答案 0 :(得分:2)

使用时

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

if中的条件绑定为false。当遇到空白字符时,要读入action的行将停止读取。如果要将空白字符读入action,则可以使用std::getline

std::getline(cin, action);

但是,这将导致另一个问题。从cin

读取的上一个调用
cin >> choice;

将在流中保留换行符。在使用std::getline之前,请确保已读取并丢弃换行符(以及换行符之前的所有其他字符)。您可以为此使用cin.ingore

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

添加

#include <limits>

能够使用std::numeric_limits

答案 1 :(得分:0)

在C ++中,cin是由空格分隔的。这意味着一旦函数遇到空格,制表符,换行符等,它将停止读取字符。要读取整行(即,在Enter上定界),请使用getline()函数,并将目标字符串传递给该函数。