0
votes

Observe this chunk of code:

#include <stdio.h>

int main(void)
{
    char choice;

    printf("\n\nDo you want to play again (Y/N)? ");
    scanf(" %c", &choice);

    if (choice != 'Y' || choice != 'y' || choice != 'N' || choice != 'n')
    {
        printf("\n\nYou didn\'t enter a decision.");
    }

return 0;
}

I want the printf() to prompt the user to input either Y or N. The scanf() will fill the user's input in the variable choice. If choice is not equal to Y, y, N, or n, it will tell the user that he/she didn't enter a decision. Then, the program will end.

However, when I inputted Y or N, it printed "You didn't enter a decision." This should only happen if I don't enter Y or N (lowercase or uppercase).

I even put a space before the conversion character so the scanf() wouldn't read the newline character (\n).

Any help would be greatly appreciated!

2
Did you try printing choice to see what character was being extracted?user123
You need to check your condition in the if statement again.Some programmer dude
I printed choice. It printed 'Y' when I inputted Y.John Vearr

2 Answers

4
votes

Change

if (choice != 'Y' || choice != 'y' || choice != 'N' || choice != 'n')  

to

if (choice != 'Y' && choice != 'y' && choice != 'N' && choice != 'n')  

otherwise whether you enter any of Y, y, N, n or any other character (as pointed by Jonathan Leffler in the comment), the expression in if will be evaluated to true.

0
votes

You Have to Just Include Else Like Following

#include <stdio.h>

int main(void)
{
    char choice;

    printf("\n\nDo you want to play again (Y/N)? ");
    scanf(" %c", &choice);

    if (choice != 'Y' || choice != 'y' || choice != 'N' || choice != 'n')
    {
        printf("\n\nYou didn\'t enter a decision.");
    }


return 0;
}