I'm using gcc in Ubuntu14. Here is my code: (test.c)
#include <stdio.h>
int main(int argc, char *argv[]){
int i=0;
for(i=1; i <argc;i++)
{
if (argv[i] = "xx") {
printf("I got you!\n");
}
printf("%d %s\n",i, argv[i]);
}
return 0;
}
I compile and run this code with:
gcc test.c -o test
./test aa bb xx
I expect the output to be
1 aa
2 bb
I got you!
3 xx
But it comes out with
I got you!
1 xx
I got you!
2 xx
I got you!
3 xx
even if I use ./test aa bb
the output is
I got you!
1 xx
I got you!
2 xx
I don't know why the output always comes out with "xx", is there anyone give me some hint, please?
What you are actually doing here is assigning "xx"
to argv[i]
and then branching on the result of that assignment. This is because the =
operator is for assignment. When testing (i.e. comparing) a value you need to use the operator for equality, which is ==
.
Also, strings cannot be compared in this manner anyway as they are not a primary data type as they are in some other languages. If you tried if (argv[i] == "xx")
you would be comparing the address of the first character of each of the strings, which would still be wrong!
To solve this we can use the strcmp()
function which compares the contents of two strings and returns a non-zero result if the strings are different. The strcmp()
function is made available by the string.h
header file.
So to achieve your intended result add #include <string.h>
at the top of your file and use if (strcmp(argv[i], "xx") == 0)
.
See this Tutorials Point page for more information on strcmp()