【问题标题】:C - getopt switch while loop and default case for invalid optionsC - getopt 切换 while 循环和无效选项的默认情况
【发布时间】:2017-09-13 03:38:19
【问题描述】:

如果键入了无效的选项/命令,我想让程序达到默认情况,但它甚至不进入 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
  • 如果你只是被stdout以某种方式缓冲,请将\n添加到所有printf字符串的末尾。
  • @John: d 不是标志。试试:./program_name -r -s foo -p

标签: c switch-statement getopt


【解决方案1】:

来自cmets:

./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]);
}

【讨论】:

    猜你喜欢
    • 2017-11-16
    • 1970-01-01
    • 1970-01-01
    • 2018-06-04
    • 1970-01-01
    • 1970-01-01
    • 2020-08-13
    • 2021-10-01
    • 1970-01-01
    相关资源
    最近更新 更多