tags:

views:

100

answers:

3

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");
    }
}
+13  A: 

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

if (strcmp(argv[1], "print") == 0) …
Konrad Rudolph
+8  A: 

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.

unwind
NULL, or simply undefined?
Oli Charlesworth
@Oli: `argv[argc]` (values at start of main) is guaranteed to be NULL by the Standard
pmg
@pmg: So it is!
Oli Charlesworth
+2  A: 

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 )

pmg
Ha... +1 for the DEADBEEF reference
It Grunt
I'd give it a +1 if you'd used 0xDECAFBAD. :-)
R..