The option string is always a string.
If you want an integer, you need to use a conversion function, like atoi(3)
So you should at least code
n = atoi(optarg);
Beware, optarg
could be NULL
and could certainly be a non-number. You might use strtol(3) which may set the ending character which you would check.
So a more serious approach could be
case 'm':
{
char* endp = NULL;
long l = -1;
if (!optarg || ((l=strtol(optarg, 0, &endp)),(endp && *endp)))
{ fprintf(stderr, "invalid m option %s - expecting a number
",
optarg?optarg:"");
exit(EXIT_FAILURE);
};
// you could add more checks on l here...
n = (int) l;
break;
}
n = optarg;
break;
Notice the assignment to l
as expression and the comma operator inside the if
test.
BTW, GNU Libc also have argp functions (and also getopt_long - but argp
functions are more powerful), which you may find more convenient. Several frameworks (notably Gtk and Qt) have also program argument passing functionalities.
If you are doing a serious program please make it accept the --help
option, and if possible the --version
one. It is really convenient, and I hate the few programs which don't accept them. See what GNU standards say.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…