Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can't seem to get my IF statement to work properly

I can't seem to get these if statements to work as intended. Whatever i input to "string answer" it always jumps into the first IF statement where the condition is set to only execute the block if the answer is exactly "n" or "N" or the block where the answer is exactly "y" or "Y". If you type in anything else it should return 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;
}
like image 999
Sauceman Avatar asked Jan 16 '26 21:01

Sauceman


1 Answers

This is not correct:

if (answer == ("n") || ("N"))

It should be

if (answer == "n" || answer == "N")

It is instructive to find out why your current code compiles though: in C++ and in C, an implicit != 0 is added to conditions that do not represent a Boolean expression. Therefore, the second part of your expression becomes

"N" != 0

which is always true: "N" is a string literal, which can never be NULL.

like image 112
Sergey Kalinichenko Avatar answered Jan 19 '26 11:01

Sergey Kalinichenko



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!