所以我正在做一个文字冒险游戏,我只是编程指导。我有一个带有南北等的脚本,然后是一条if语句,该语句表明如果用户输入的不是方向,它会说这不是方向,并循环到顶部,但不起作用。即使我输入正确的输入,也将始终打印那不是方向。有人可以帮忙吗?
#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;
}
Run Code Online (Sandbox Code Playgroud)
正如我在评论中所说:
在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") {...}
Run Code Online (Sandbox Code Playgroud)
对于如果是:
if (input != "n" || input != "s" || input != "e" || input != "w") {...}
Run Code Online (Sandbox Code Playgroud)