Reputation: 25
I am working on a program where I get the name of a file from the input in a command line. I need to check if the input is a given character say "-" and work with the file according to this result, but I am not quite sure how to do it. The method I have tried, which seemed to logically make sense, of just checking if
argv[1] == "-";
always returns zero, even when I write "-" in the command input. What can I do?
Upvotes: 1
Views: 4438
Reputation: 30136
The expression argv[1]
is the address of a (null-terminated) array of characters.
The expression "-"
is the address of another (null-terminated) array of characters.
These addresses are not equal, hence the expression argv[1] == "-"
is always false.
That said, here is an alternative approach for checking if the input is a given character:
if (argv[1][0] != 0 && argv[1][1] == 0)
{
switch (argv[1][0])
{
case '-':
...
break;
case '+':
...
break;
case '=':
...
break;
...
}
}
Upvotes: 1
Reputation: 26496
you need to write
strcmp(argv[1],"a")==0;
in your example, you compared two pointers , not two strings.
when compiling, the compiler declares "a" somewhere in the memory , then subsitute it in compile time with its memory address. since argv[1] can't really sit on the same byte with (temporary) "a" , the result is always false.
you need to iterate over the two strings and iterativly compare each character.
strcmp
compares 2 strings and return 0 if they are equale in this exact manner.
for more info on strcmp
: http://www.cplusplus.com/reference/cstring/strcmp/
in order to handle multiple characters, you can place few if-else's :
if (strcmp(argv[1],"-")==0){
minus_character_handling_function();
} else if (strcmp(argv[1],"+")==0){
plus_character_handling_function();
} else if (strcmp(argv[1],"a")==0){
a_character_handling_function();
}
Upvotes: 3
Reputation: 33252
by doing this check:
argv[1] == "-";
you are comparing the address in which is contained the firrst argument of the command line, and the address of the literal "-"
you have in your program, and they are different, so this is the reason your test fails. You actually want to compare the charachters contained in memory location started by these two addresses, and this is done by function of the strcmp
family.
Upvotes: 0