【发布时间】:2017-09-13 03:38:19
【问题描述】:
如果键入了无效的选项/命令,我想让程序达到默认情况,但它甚至不进入 while 循环。我想知道我做错了什么,以及我需要改变什么才能让它工作,它只有在使用正确的情况下才有效。 :)
#include <stdio.h>
#include <stdlib.h>
#include <getopt.h>
#include <string.h>
int main (int argc, char *argv[]){
const char *optstring = "rs:pih";
char option;
while ((option = getopt(argc, argv, optstring)) != EOF) {
printf("I'm in the while loop!");
switch (option) {
case 'r':
break;
case 's':
printf("Second Argument: %s", optarg);
break;
case 'p':
printf("p");
break;
case 'i':
printf("i");
break;
case 'h':
printf("h");
break;
default:
printf("nothing");
}
}
return 0;
}
【问题讨论】:
-
对我来说似乎工作得很好。请发布您的测试用例。
-
我的测试用例是 ./program_name d
-
如果你只是被
stdout以某种方式缓冲,请将\n添加到所有printf字符串的末尾。 -
@John:
d不是标志。试试:./program_name -r -s foo -p
标签: c switch-statement getopt