C - getopt 切换 while 循环和无效选项的默认情况
C - getopt switch while loop and default case for invalid options
我想让程序在输入无效 option/command 时触发默认大小写,但它甚至不进入 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
doesn't have a flag. Try: ./program_name -r -s foo -p
您还可以通过以下方式打印未解析的剩余选项:
for (int i = optind; i < argc; i++) {
printf("remaining argument[%d]: %s\n", i, argv[i]);
}
我想让程序在输入无效 option/command 时触发默认大小写,但它甚至不进入 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
doesn't have a flag. Try: ./program_name -r -s foo -p
您还可以通过以下方式打印未解析的剩余选项:
for (int i = optind; i < argc; i++) {
printf("remaining argument[%d]: %s\n", i, argv[i]);
}