C - Compare two characters

I'm having trouble comparing two characters. I wrote a very basic C problem to try command line arguments.

Here is my code:

#include <stdio.h> #include <unistd.h> int main(int argc, char *argv[]) { char ch; char *type = ""; char *gender = ""; int baby = 0; int count = 0; /* Options: * -t = type of pet * -g = gender * -b = baby or adult */ while ((ch = getopt(argc, argv, "t:g:b")) != EOF) switch (ch) { case 't': type = optarg; break; case 'g': gender = optarg; break; case 'b': baby = 1; break; default: fprintf(stderr, "Invalid option.\n"); return 1; } argc -= optind; argv += optind; printf("You have chosen a %s.\n", type); if (gender == 'f') puts("It a girl"); if (gender == 'b') puts("It a boy."); // The main command line arguments should be about the traits of the pet printf("%s", "Traits: "); for (count = 0; count < argc; count++) printf("%s ", argv[count]); return 0; } 

So, if I enter it into the terminal:

  $ ./pet_shop -t dog -gf cute small 

I get this as output:

  You have chosen a dog: Traits: cute small 

At the exit, he does not have information about sex, it must be a girl since I entered f. But I tried to check printf ("% i", gender), which gave the value 0. Is g == 'f' used to compare two characters?

+7
source share
4 answers

gender is char* , that is, a pointer to the first charadcter of the string. When you compare this to a single char , both the char and the pointer are converted to integers and an integer comparison is performed.

To compare strings, use strcmp from <string.h> :

 if (strcmp(gender, "f") == 0) // it a girl 

Note the double quotation mark ( " ), which denotes a string, not a single character.

+15
source

You have:

 char *gender = ""; 

So gender is a string, not a character. To compare strings, use strcmp .

+4
source

First you declared gender as a string:

 char *gender = ""; 

Then you later relate to one character:

 if(gender == 'f') [...] if(gender == 'b') 

You need to make clear in your mind what gender is before trying to code it.
Choose one definition and stick to it.

+4
source

The problem is that you are comparing a string (or rather, a char* ) with char . This comparison (i.e. if(gender == 'f') ) will compare the original pointer value with the character instead of comparing the contents of the string with the character. Instead, you need to dereference the pointer and then compare that value or index to a string, i.e. if(gender[0] == 'f') .

Of course, it would be nice to check that the line really contains something before trying to do this in order to avoid segfault.

+3
source

All Articles