gpt4 book ai didi

c++ - 我的 if 语句打印在我的 while 循环中的每个 if 语句上,不管它是否为 false

转载 作者:行者123 更新时间:2023-12-03 18:31:50 25 4
gpt4 key购买 nike

所以我正在制作一款文字冒险游戏,我只是提供编程指导。我有一个南北等脚本。然后是一个 if 语句,如果用户输入的不是方向,它会说这不是方向并循环到顶部,但它不起作用。即使我输入正确的输入,它也会始终打印 That is not a direction。谁能帮忙?

#include <iomanip>
#include <string>
#include <iostream>
using namespace std;



int main()
{
string input;
while (input != "north", "n", "south", "s", "east", "e") {
cout << "Enter a direction" << endl;
getline(cin, input);
if (input == "north" || input == "n") {
cout << "north" << endl;
}
if (input == "west" || input == "w") {
cout << "west" << endl;
}
if (input == "east" || input == "e") {
cout << "east" << endl;
}
if (input == "south" || input == "s") {
cout << "south" << endl;
}
if (input != "n", "s", "e", "w")
{
cout << "That is not a direction" << endl;
}
}
return 0;
}

最佳答案

正如我在评论中所说:

在 C++ 中,"north"、"n"、"south"、"s"、"east"、"e" 将始终计算为 "e""n"、"s"、"e"、"w" 将始终评估为 "w"

(对于所有可能的情况)进行这种比较的正确方法是:

 while (input != "north" && input != "n" && input != "south" && input != "s" && input != "east" && input != "e" && input != "west" && input != "w") {...}

如果是:

if (input != "n" || input != "s" || input != "e" || input != "w") {...}

Demo

关于c++ - 我的 if 语句打印在我的 while 循环中的每个 if 语句上,不管它是否为 false,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59098967/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com