Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Comparing user-inputted characters in C

Tags:

c

char

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.

like image 343
Joe Scho Avatar asked Oct 12 '10 04:10

Joe Scho


People also ask

Can I use == to compare characters in C?

Compare Char in C Using the strcmp() Function in C The strcmp() function is defined in the string header file and used to compare two strings character by character. If both strings' first characters are equal, the next character of the two strings will be compared.

How do you compare user inputs to strings?

The right way of comparing String in Java is to either use equals(), equalsIgnoreCase(), or compareTo() method. You should use equals() method to check if two String contains exactly same characters in same order. It returns true if two String are equal or false if unequal.

How do you compare chars in if condition?

You're doing it in the right way but your input is expecting a string instead of a char, just change it like so: scanf("%c",&a); And you're ready to go!

Can you compare two chars?

The compare(char x, char y) method of Character class is used to compare two char values numerically. The final value returned is similar to what would be returned by: Character. valueoOf(x).


1 Answers

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') {
like image 169
codaddict Avatar answered Oct 06 '22 21:10

codaddict