似乎无法使我的IF语句正常工作

Sau*_*man 2 c++ if-statement conditional-operator conditional-statements

我似乎无法获得这些if语句按预期工作.无论我输入"字符串答案",它总是跳转到第一个IF语句,其中条件设置为仅在答案正好为"n"或"N"时执行块或者答案恰好为"y"的块或"Y".如果你输入任何其他内容,它应该返回0.

    // Game Recap function, adds/subtracts player total, checks for deposit total and ask for another round
    int gameRecap() {
    string answer;
    answer.clear();

    cout << endl << "---------------" << endl;
    cout << "The winner of this Game is: " << winner << endl;
    cout << "Player 1 now has a total deposit of: " << deposit << " credits remaining!" << endl;
    cout << "-------------------------" << endl;

    if (deposit < 100) {
       cout << "You have no remaining credits to play with" << endl << "Program will now end" << endl;
       return 0;       
    }
    else if (deposit >= 100) {
       cout << "Would you like to play another game? Y/N" << endl;
       cin >> answer;
       if (answer == ("n") || ("N")) {
          cout << "You chose no" << endl;
          return 0;
       }
       else if (answer == ("y") || ("Y")) {
          cout << "You chose YES" << endl;
          currentGame();
       }
       else {
            return 0;
       }
       return 0;
    }
    else {
         return 0;
    }
return 0;
}
Run Code Online (Sandbox Code Playgroud)

das*_*ght 9

这不正确:

if (answer == ("n") || ("N"))
Run Code Online (Sandbox Code Playgroud)

它应该是

if (answer == "n" || answer == "N")
Run Code Online (Sandbox Code Playgroud)

找出当前代码编译的原因是有益的:在C++和C中,隐式!= 0被添加到不表示布尔表达式的条件中.因此,表达式的第二部分变为

"N" != 0
Run Code Online (Sandbox Code Playgroud)

总是true:"N"是一个字符串文字,永远不会NULL.


jon*_*ins 5

||运营商不工作,你似乎认为它的方式.

if (answer == ("n") || ("N"))
Run Code Online (Sandbox Code Playgroud)

正在检查是否answer"n",如果不是,它正在评估"N"为布尔值,在这种情况下始终为真.你真正想做的是

if (answer == ("n") || answer == ("N"))
Run Code Online (Sandbox Code Playgroud)

你也应该做类似调整针对检查"y""Y".