if和if-else语句不适用于c ++

The*_*Elf 0 c++ if-statement text-based

所以我的朋友和我正在尝试制作一个基于文本的视频游戏,我一直在研究如何降低编程.这是我们迄今为止的c ++程序:

#include <iostream>
#include <stdio.h>

char Choice;

using namespace std;

int main()
{
    printf("You wake up to darkness.\n");
    printf("Confused and tired, you walk to the nearest house.\n");
    printf("You notice it's abandoned. What do you do?\n");
    printf("1. Walk Away.\n");
    printf("2. Jump.\n");
    printf("3. Open Door.\n");
    printf("Choose wisely.\n");
    cin >> Choice;

    if(Choice=1)
    {
        printf("The House seems to have a gravital pull on you. How strange.\n");
    }

    else if(Choice=2)
    {
        printf("Having Fun?\n");
    }

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

但是当我构建并运行它时,它将显示所有内容,但所有答案都将是if(Choice = 1)答案.我的程序中是否缺少某些需要或部分相互矛盾的东西?

Joh*_*ica 7

您需要比较运算符==,而不是赋值运算符=.这些是不同的运营商.使用=会改变Choice你想要的值,而不是你想要的.(您的编译器应警告您=if语句中的使用.)

1是整数1.您想要检查字符'1'(ASCII值49),这是不同的.用'1'而不是1.

if (Choice == '1')
{
    printf("The House seems to have a gravital pull on you. How strange.\n");
}
else if (Choice == '2')
{
    printf("Having Fun?\n");
}
Run Code Online (Sandbox Code Playgroud)

此外,您正在混合两种类型的I/O. 使用cin输入还是不错的.你应该使用它的对应物cout来输出,而不是printf.

cout << "You wake up to darkness." << endl;
cout << "Confused and tired, you walk to the nearest house." << endl;
Run Code Online (Sandbox Code Playgroud)