问题描述:

Why is my code under giving me back "Not a valid command" when i give the argument print ?

int main(int argc, char *argv[]) {

printf("Argument 2 er %s\n", argv[1]);

if(argv[1] == "print") {

printf("Print kommando kalt");

} else if(argv[1] == "random") {

printf("Random kommando kalt");

} else if(argv[1] == "replace") {

printf("Replace kommando kalt");

} else if(argv[1] == "remove") {

printf("Remove kommando kalt");

} else if(argv[1] == "len") {

printf("øem kommando kalt");

} else {

printf("Ingen gyldig kommando\n");

}

}

网友答案:

You cannot compare C strings using ==. This only does a pointer comparison. You need to use strcmp instead:

if (strcmp(argv[1], "print") == 0) …
网友答案:

Because you cannot compare strings like that in C.

You need to use:

if(strcmp(argv[1], "print") == 0)
  printf("Print kommando kalt\n");

And so on.

Also, make sure you don't access argv[1] without making sure it's really there and valid; if your program gets called with no arguments it will be NULL. You can use the value of argc to determine how many arguments you got.

网友答案:

Because argv[1] is a char*: something like 0xDEADBEEF
and "print" behaves as if it is another char*: something like 0xBADF00D

and 0xDEADBEEF != 0xBADF00D

You want to use strcmp() ( http://linux.die.net/man/3/strcmp )

相关阅读:
Top