#include <stdio.h>
#include <stdlib.h>
#include <getopt.h>
#include <string.h>
int main(int argc, char **argv) {
int o;
int w = 10;
while ((o = getopt(argc, argv, "w::")) != -1) {
switch (o) {
case 'w' :
if (optarg) {
w = atoi(optarg);
}
break;
}
}
printf("%d\n", w);
}
我想要这个工作
$ gcc -Wall theup.c
$ ./a.out -w 17
17
目前正在这样做
$ gcc -Wall theup.c
$ ./a.out -w 17
10
有没有办法用getopt做到这一点?它适用于大多数人,例如-w17 -w,但是空格不起作用
最佳答案
与::
(不允许在选项后传递值)和空格之间,在-w 17
(其中17
是选项的值)和-w 17
(其中17
是另一个值)之间将存在歧义参数,该参数说明getopt需要在使用::
时对值进行整理
更糟糕的是,想想一般情况下还有其他选择。 -w -x
会做什么? getopt
无法预测您在选择选项后是否需要输入号码。
我只是将getopt行更改为:
while ((o = getopt(argc, argv, "w:")) != -1) {
现在省略
-w
仍会给出10
,因为该值是默认值。
关于c - getopt灵活性使空间也能正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49022252/