getopt switch语句永远不会遇到默认情况

我试过搜索,但没有找到重复/类似的问题。

为什么“默认”在这种情况下永远不会触发? 为一个课程做一些以前的家庭作业,为秋天做准备,我在C中遇到了getopt()的问题。

以下是有问题的特定行:

while ((c = getopt(argc, argv, "i:o:")) != -1) { switch (c) { case 'i': inFile = strdup(optarg); break; case 'o': outFile = strdup(optarg); break; default: usage(); //this prints the "usage" statement and exits cleanly. } } 

我的问题是,怎么称呼

 ./fastsort abcd 

不打印使用并退出?

以下代码将搜索-i hello或/和-o world

 while((c = getopt(argc, argv, "i:o:") != -1) 

但是你正在执行的是:

 ./fastsort abcd 

其中getopt(argc, argv, "i:o:") != -1不满意,因为传递的参数abcd都不是一个选项

我想通了,觉得自己像个白痴:

由于永远不会给出任何有效的参数/标志,因此while循环甚至不执行。 我事先添加了一点检查,似乎解决了一些问题:

 //Check number of args if(argc < 5 || getopt(argc, argv, "i:o:") == -1){ usage(); } 

编辑:刚刚意识到它还没有完成。 现在,由于我过早地调用了getopt,它过早地抛出了一个args,因此没有正确地设置正确的。

我的新“解决方案”(尽管有点笨拙)是:

 -Initialize inFile and outFile to null -Do the while loop as in my original post -If inFile or outFile are still null, print usage 

它通过了所有自动化测试。