gpt4 book ai didi

c - getopt switch 语句永远不会达到默认情况

转载 作者:太空宇宙 更新时间:2023-11-04 02:03:00 26 4
gpt4 key购买 nike

我已经尝试搜索但没有找到重复/类似的问题。

为什么在这种情况下“默认”永远不会触发?我正在为秋季类(class)做一些以前的家庭作业,但我在使用 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 a b c d

不打印用法并退出?

最佳答案

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

因为从来没有给出任何有效的参数/标志,while 循环甚至不执行。我只是事先添加了一点检查,它似乎解决了问题:

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

编辑:刚刚意识到它还不能正常工作。现在,由于我过早调用 getopt 一次,它会过早地丢弃其中一个参数,因此无法正确设置正确的参数。

我的新“解决方案”(虽然有点老套)是:

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

并且它通过了所有给定的自动化测试。

关于c - getopt switch 语句永远不会达到默认情况,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24377008/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com