14

The program works like this, argument is supplied in a form like this at the beginning:

-w cat

The string "cat" is stored in variable pattern and for each letter that is followed by - we do something; in this case we set mode = W. What I have trouble with is when the argument is in the form:

-w -s -n3,4 cat

Now I believe that as before mode is set to W,S and N in the order that is read. And If I wanted to store/remember what order sequence of letters mode was set to after the loop is done, I can store the information in an array. Also as should be done pattern is assigned the string "cat". Correct me if I am wrong or is there an easier way to do this.

Secondly, I want to be able to access and store the numbers 3 and 4. I am not sure how that is done and I am not sure what argc -= optind; and argv += optind; does. Except that I think the arguments are stored in a string array.

enum MODE {
    W,S,N
} mode = W;
int c;
while ((c = getopt(argc, argv, ":wsn")) != -1) {
    switch (c) {
        case 'w': 
            mode = W;
            break;
        case 's': 
            mode = S;
            break;
        case 'n':
            mode = N;
            break;   
    }
}
argc -= optind; 
argv += optind; 

string pattern = argv[0];

Update: figured out how to access the numbers, I just had to see what was in argv during the loop. So I guess I will just store the value I find there in another variable to use.

3
  • 2
    May I recommend getopt_long or, even better, boost::program_options. Commented Sep 23, 2018 at 15:25
  • Also take a look at this library named Clara.. it looks cool! Commented Sep 23, 2018 at 15:29
  • 1
    Thanks, but I have to use getopt :( Commented Sep 23, 2018 at 16:00

1 Answer 1

13

getopt sets the global variable optarg when a parameter with a value has been provided. For example:

for(;;)
{
  switch(getopt(argc, argv, "ab:h")) // note the colon (:) to indicate that 'b' has a parameter and is not a switch
  {
    case 'a':
      printf("switch 'a' specified\n");
      continue;

    case 'b':
      printf("parameter 'b' specified with the value %s\n", optarg);
      continue;

    case '?':
    case 'h':
    default :
      printf("Help/Usage Example\n");
      break;

    case -1:
      break;
  }

  break;
}

See here for a more complete example.

I want to be able to access and store the numbers 3 and 4.

Since this is a comma delimited list you will need to parse optarg for the tokens (see strtok) and then use atoi or similar to convert each one to an integer.

Sign up to request clarification or add additional context in comments.

Comments