Joe Scho Joe Scho - 2 months ago 8
C Question

Comparing user-inputted characters in C

The following code snippets are from a C program.

The user enters Y or N.

char *answer = '\0';

scanf (" %c", answer);

if (*answer == ('Y' || 'y'))
// do work


I can't figure out why this
if
statement doesn't evaluate to true.

I checked for the y or n input with a
printf
and it is there, so I know I'm getting the user input. Also when I replace the the condition of the if statement with 1 (making it true), it evaluates properly.

Answer

I see two problems:

The pointer answer is a null pointer and you are trying to dereference it in scanf, this leads to undefined behavior.

You don't need a char pointer here. You can just use a char variable as:

char answer;
scanf(" %c",&answer);

Next to see if the read character is 'y' or 'Y' you should do:

if( answer == 'y' || answer == 'Y') {
  // user entered y or Y.
}

If you really need to use a char pointer you can do something like:

char var;
char *answer = &var; // make answer point to char variable var.
scanf (" %c", answer);
if( *answer == 'y' || *answer == 'Y') {