Home > Net >  Getopt does not read repetitive argument
Getopt does not read repetitive argument

Time:07-24

I am trying to get options via getopt.

I`ve run the program via the command line:

test.exe -ja 1:2 -ja 3:4

My code have following:

int c;
while ((c = getopt (argc, argv, "j:")) != -1) {
    switch (c) {
        case 'j': {
            printf("Find j\n");
            if (optarg[0] == 'a') {
                printf("Find a\n");
            }
            break;
        }
    }
}

The problem is that case 'j' triggered only once, not twice. What should i change to read every -ja option?

CodePudding user response:

From the man page:

If there are no more option characters, getopt() returns -1.

When you pass test.exe -ja 1:2 -ja 3:4, you are passing multiple option elements (a and 1:2) to a single option j. As they are not quoted, getopt() finds option j and sets optarg to point at a, the first character of the option element.

It then finds 1:2 which is not an option and returns -1.

Quote your arguments like test.exe -j "a 1:2" -j "a 3:4" and it's triggered twice:

test.exe -j "a 1:2" -j "a 3:4"
Find j
Find a
Find j
Find a
  • Related