Reputation: 960
I'm a C amateur, and am tasked to write a program that takes command line arguments, one of which must be either the character 'N' or the character 'A'. This is the method that I thought would work effectively:
//check argv[2], valid should be 1 at this point if argv[1] is an integer
printf("Valid is currently: %d, valid);
printf("The second argument is: %s, argv[2]);
if(argv[2] != "N" && argv[2] != "A") { valid = 0; }
printf("Valid is currently: %d, valid");
Given the input ./a.out 4 A
, and using printf
statements before and after the given if statement, I achieve the following output:
Valid is currently: 1
The second argument is: A
Valid is currently: 0
I thought this would effectively make the valid-invalid bit invalid only if argv[2] wasn't "N" or "A", but it's not working. Then I tried to use strcmp
in a similar code snippet, to unsuccessful results.
This is my first undertaking in C, so please be gentle, but I've tried everything from changing "
to '
, using strcmp
instead of !=
, and even using atoi
, although I don't know if I used it properly. Is there something inherent in C string input or comparison I'm not understanding?
Upvotes: 1
Views: 83
Reputation: 38586
To compare it as a string, try:
if (strcmp(argv[2], "N") != 0 && strcmp(argv[2], "A") != 0)
// can be reduced to:
if (strcmp(argv[2], "N") && strcmp(argv[2], "A"))
Or you can also compare it as a single character:
if (argv[2][0] != 'N' && argv[2][0] != 'A')
But that's probably not as versatile.
Upvotes: 3