Frage

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;
}
War es hilfreich?

Lösung

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.

Andere Tipps

The || operator does not work the way you seem to think it does.

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

is checking if answer is "n", and if not, it is evaluating "N" as a boolean, which in this case is always true. What you really want to do is

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

You should also make similar adjustments for the check against "y" and "Y".

This part is not evaluating correctly:

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

Shold be:

if (answer == "n" || answer == "N") {}
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top