0

I want to be able to get 2 values for -a arg like: -a min max

I have the following code:

while((opt = getopt(argc,argv,"a:c:k:rv")) != -1)
{
    switch (opt)
    {
         case 'a':
                min = atoi(optarg);
                fprintf( stderr,"value1: %s\n", optarg);
                optind--;
                for( ;optind < argc && *argv[optind] != '-'; optind++)
                {
                    optind++;
                    fprintf( stderr,"value2: %s\n", optarg);
                    max = atoi(optarg);
                }
            break;
          //other cases
     }
}

How can I get multiple values for a single argument?

6
  • 1
    You would need to modify getopt. Adopting syntax like -a min:max would be much easier. Aug 29, 2013 at 15:22
  • will this affect my other args syntax ?
    – Sam Reina
    Aug 29, 2013 at 15:28
  • No it won't, why should it? You of course need to parse it yourself but this is very easy with e g. strtok. Aug 29, 2013 at 15:47
  • is there any other way? I don't like using strtok
    – Sam Reina
    Aug 29, 2013 at 15:50
  • sscanf(optarg, "%d:%d", &min, &max) should also work. If you don't like it, use strtol and check the remainder string. Aug 29, 2013 at 16:16

1 Answer 1

1

The easiest way to accept two parameters of an option is to join them with a non-blank character like ':':

myprogram -a min:max other-options

This way getopt thinks of it as of a single parameter. When you handle it you need to separate it in two yourself. If both halves are numbers, then this should work:

if (sscanf(optarg, "%d:%d", &min, &max) != 2)
  /* report an error */

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.