user9111757
user9111757

Reputation:

Using getopt() in C++ to handle arguments

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.

Upvotes: 14

Views: 49107

Answers (1)

Geoffrey
Geoffrey

Reputation: 11353

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.

Upvotes: 12

Related Questions