繁体   English   中英

C-循环时使用getopt切换,无效选项的默认情况

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM