【问题标题】:Why is this only returning "yes"为什么这只返回“是”
【发布时间】:2016-12-05 06:01:39
【问题描述】:
int OnLoad() {
cout << "Hi whats your name? ";
cin >> name;
system("cls");
cout << "Hi " << name << "." << " Are you here to Take Over the city from zombies?"<< endl;
cin >> userInput;
if (userInput == "yes" || "Yes") {
    cout << "Yes" << endl;
}
else if (userInput == "no" || "No") {
    cout << "No" << endl;
}
else {
    cout << "I don't understand." << endl;
}
return 0;
}

int main() {
OnLoad();
system("pause");
return 0;
}

此代码仅返回是,在控制台窗口弹出并询问你是否在这里从僵尸手中接管城市后,即使我输入否它返回是!

【问题讨论】:

  • || "Yes" 不会按照你的想法去做。它实际上总是评估为真!你想要if ( (userInput == "yes") || (userInput == "Yes"))
  • 我确信这个问题有数百个(如果不是数千个)重复,所以我不会发布正式答案。
  • 谢谢,其实我已经开始尝试这个了,但我认为这是错误的。大声笑。

标签: c++ console-application


【解决方案1】:

|| 不是这样的运算符有效,如果您只是将“是”作为条件,它将始终评估为真

if (userInput == "yes" || userInput == "Yes") {
    cout << "Yes" << endl;
}

原因是因为优先

userInput == "yes"

userInput == "Yes"

在 || 之前得到评估(逻辑或)

【讨论】:

    【解决方案2】:
    if (userInput == "yes" || "Yes")
    

    其实就是

    if ((userInput == "yes") || ("Yes"))
    

    这是两个表达式之间的逻辑 OR:userInput == "yes""Yes"。第一个是正确的,直接计算为bool。第二个只是一个char*,它将隐式转换为bool。因为它是一个编译时字符串,所以它不能是nullptr,这意味着它总是会评估为true。反过来,这意味着整个条件始终为true(这就是逻辑 OR 的工作原理)。 正确的代码是

    if (userInput == "yes" || userInput == "Yes")
    

    P。 S. 这就是为什么我总是建议使用可能的最高警告级别进行编译(/W4 用于 MSVC,-Wall -pedantic-errors 用于 GCC 和 clang)。在这种情况下,大多数编译器都会生成警告。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-12-30
      • 1970-01-01
      • 1970-01-01
      • 2023-03-05
      • 2021-07-17
      • 1970-01-01
      • 2022-01-22
      • 1970-01-01
      相关资源
      最近更新 更多