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?
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:
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:
And it passed all of the automated tests given.
The below code will search for options like
-i hello
or/and-o world
However what you are executing is:
where
getopt(argc, argv, "i:o:") != -1
is not satisfied since none of the passed argumenta b c d
is an option