Reputation: 11
I would like to check the arguments in argv[]
, but it fails to check the second character.
For example,
I can do that:
int main(int argc, char *argv[]){
if (*argv[1] == "A")
printf("Hello: %s\n", argv[1]);
}
However, I can't check argv[1]
when I change "A" to "AB" like this:
if (*argv[1] == "AB")
printf("Hello: %s\n", argv[1]);
}
Upvotes: 0
Views: 1085
Reputation: 27233
On this line:
if (*argv[1] == "AB")
you're comparing a char
to char*
. These are different types. Also, even if the first operand was char*
you should still not use ==
to compare strings since it merely compares the pointer values. Use strncmp()
instead
if (strncmp("AB", argv[1], 2) == 0)
This condition is true if two first characters of argv[1]
are "AB"
, e.g. if argv[1]
is "ABC"
. If you want to check that argv[1]
is exactly "AB"
use strcmp()
like this
if (strcmp("AB", argv[1]) == 0)
Note that it is fine to use ==
to compare single characters:
if (argv[1][0] == 'A')
Also, before you assume argv[1]
is valid you should check argc
to ensure you have actually been given an argument.
Upvotes: 1
Reputation: 143099
You should stop comparing pointers and characters, this isn't healthy.
You can do *argv[1]=='A'
. And when it comes two two characters, you should use strncmp
.
Upvotes: 0
Reputation: 5456
*argv[1]
is a char
. you should not compare it to string (char*
). If you want you check if it's A, do if (*argv[1]=='A')
If you want to check the whole argument, do it like strcmp(argv[1],"AB")
Upvotes: 0
Reputation: 399863
Strings are compared with strcmp()
in C, almost never with ==
:
if(strcmp(argv[1], "AB") == 0)
printf("the second argument is AB\n");
Note that 0 is returned when the compared strings are equal.
Upvotes: 3