#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' :
w = atoi(optarg);
break;
}
}
printf("%d\n", w);
}
基本上,如果没有输入任何内容,我希望 -w 具有。
考虑这些用例
$ gcc -Wall fileabove.c
$ ./a.out
10
$ ./a.out -w
10
$ ./a.out -w14
14
我无法让第二个工作。有什么方法可以使用 getopt 来获得预期的结果吗?
最佳答案
假设您正在使用 GNU getopt,以下内容应该可以工作:
while ((o = getopt(argc, argv, "w::")) != -1) {
switch (o) {
case 'w' :
if (optarg) {
w = atoi(optarg);
}
break;
以下 :
将该选项标记为需要参数。双 :
使参数可选(这是 GNU 扩展)。如果没有参数,optarg
为 NULL
。
关于c - getopt 如何设置默认值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49021769/