Can anyone tell me why I'm getting "number 1" as my output when i enter arguments 1, 2, 3. It seems like its always 1 and I don't know why.

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

         if (argv[1] = "1"){
            printf("number 1");
         }else if(argv[1] = "2"){
            printf("number 2");
         }else if(argv[1] = "3"){
            printf("number 3");
         }else{
            printf("Missing a case number");
         }
}

Recommended Answers

All 6 Replies

Use strcmp to compare strings.

Can anyone tell me why I'm getting "number 1" as my output when i enter arguments 1, 2, 3. It seems like its always 1 and I don't know why.

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

         if (argv[1] = "1"){
            printf("number 1");
         }else if(argv[1] = "2"){
            printf("number 2");
         }else if(argv[1] = "3"){
            printf("number 3");
         }else{
            printf("Missing a case number");
         }
}

It is because you are assigning the value to argv[1] every time in your if condition. Use == instead of =

It is because you are assigning the value to argv[1] every time in your if condition. Use == instead of =

Wrong. As Dave said, comparison of char arrays (aka "C style strings") should usually use strcmp() rather than ==.

Don't forget to check argc value before argv[1] using, for example:

if (argc > 1) {
    switch (*argv[1]) {
    case '1':
          ...
          break;
    case '2':
        ...
    default:
        ...
    }
} else {
    /* argv[1] is NULL! */
}

Also, argv is of type char**... so use strcmp to compare the strings...

Thanks for the help guys :)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.