[英]C - getopt switch while loop and default case for invalid options
我想讓程序在鍵入無效的選項/命令時命中默認情況,但它甚至沒有進入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
沒有標志。 試試:./program_name -r -s foo -p
您還可以打印未通過以下方式解析的其余選項:
for (int i = optind; i < argc; i++) {
printf("remaining argument[%d]: %s\n", i, argv[i]);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.