John Vearr
John Vearr

Reputation: 13

Scanf() does not recognize space before %c

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!

Upvotes: 0

Views: 192

Answers (2)

user3957230
user3957230

Reputation:

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;
}

Upvotes: 0

haccks
haccks

Reputation: 106102

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.

Upvotes: 5

Related Questions