当我不写参数的情况下,我有一个问题,我希望这是必要的。
while ((choice = getopt(argc, argv, "a:b:")) != -1) {
switch (choice) {
case 'a' :
printf("a %s\n", optarg);
break;
case 'b' :
printf("b %d\n", optarg);
break;
case '?' :
if (optopt == 'a')
fprintf (stderr, "Option -%c requires an argument.\n", optopt);
break;
}
}
当我编写./a.out -b test
时,我看不到fprintf()
消息
发布于 2012-05-04 20:52:28
我认为您需要跟踪您自己是否使用过选项-a
- getopt()
没有足够丰富的规范来捕获该信息。类似于:
int opt_a_found = 0;
while ((choice = getopt(argc, argv, "a:b:")) != -1) {
switch (choice) {
case 'a' :
opt_a_found = 1;
printf("a %s\n", optarg);
break;
case 'b' :
printf("b %d\n", optarg);
break;
case '?' :
if (optopt == 'a')
fprintf (stderr, "Option -%c requires an argument.\n", optopt);
break;
}
}
if (!opt_a_found) {
fprintf (stderr, "Option -a is required.\n");
}
发布于 2012-05-04 19:11:40
假设您在编写fprintf()
时指的是printf()
我可能错了,但据我所知,optarg
是char *
,所以你应该在你的第二个printf()
中也使用%s
。
如果你真的指的是fprintf()
,请解释为什么你希望看到它。
发布于 2012-05-04 19:25:35
因为您的fprintf
处于此条件if (optopt == 'a')
下,当optopt为'b'
时,该条件将为false
if (optopt == 'a')
fprintf (stderr, "Option -%c requires an argument.\n", optopt);
break;
试一试
if (optopt == 'a' || optopt == 'b' )
fprintf (stderr, "Option -%c requires an argument.\n", optopt);
break;
https://stackoverflow.com/questions/10454682
复制相似问题