I am having trouble comparing two characters. I've written a very basic C problem to try out command line arguments.
Here is my code so far:
#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's a girl");
if (gender == 'b')
puts("It's 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 type this into the terminal:
$ ./pet_shop -t dog -g f cute small
I get this as output:
You have chosen a dog:
Traits: cute small
The output it missing information about the gender, it should be a girl since I entered f. But I tried checking by printf("%i", gender) which gave the value 0. Is g == 'f' the incorrect way of comparing two characters?
Yes, char is just like any other primitive type, you can just compare them by == .
You can't compare strings in C with ==, because the C compiler does not really have a clue about strings beyond a string-literal.
gender
is a char*
, i.e. a pointer to a string's first charadcter. When you compare that to a single char
, both the char
and the pointer are converted to integers and an integer comparison is done.
To compare strings, use strcmp
from <string.h>
:
if (strcmp(gender, "f") == 0)
// it's a girl
Note the double quote ("
) which signifies a string, rather than a single character.
The problem is that you're comparing a string (or rather, a char*
) to a char
. This comparison (i.e. if(gender == 'f')
) will compare the raw pointer value to the character instead of comparing the contents of the string to the character. Instead, you need to dereference the pointer and then compare that value, or index into the string, i.e. if(gender[0] == 'f')
.
Of course, it would also be a good idea to check that the string actually contains something before attempting that in order to avoid a segfault.
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