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.
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.
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.
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!
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).
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') {
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With