getopt switch statement never hitting default case

匆匆过客 提交于 2020-01-03 04:07:31

问题


I've tried searching and haven't found a duplicate/similar question.

How come "default" is never triggering in this case? Working on some previous homework assignments for a course to prepare for the fall, and I'm having an issue with getopt() in C.

Here are the particular lines in question:

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.
        }
    }

My issue is, how come calling

./fastsort a b c d

doesn't print the usage and exit?


回答1:


The below code will search for options like -i hello or/and -o world

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

However what you are executing is:

./fastsort a b c d

where getopt(argc, argv, "i:o:") != -1 is not satisfied since none of the passed argument a b c dis an option




回答2:


I figured it out, and feel like an idiot:

Since there are never any valid arguments/flags given, the while loop doesn't even execute. I just added a little check beforehand, and it seemed to fix things:

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

Edit: Just realized it's not quite yet working. Now, since I'm calling getopt once too soon, it's dumping one of the args prematurely, thus not setting correct ones properly.

My new "solution" (albeit a bit hacky) is:

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

And it passed all of the automated tests given.



来源:https://stackoverflow.com/questions/24377008/getopt-switch-statement-never-hitting-default-case

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!