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?
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 */