【问题标题】:getopt_long not printing error messagegetopt_long 不打印错误消息
【发布时间】:2018-02-15 15:25:34
【问题描述】:

我正在使用 getopt 和 getopt_long 来解析 c++ 程序的参数。当参数正确给出时,我没有问题。此外,当给出错误的短参数时,错误消息会正确打印。但是当给出错误的长参数时,我没有收到它的错误消息。

代码如下:

#include <stdio.h>
#include <ctype.h>
#include <getopt.h>

static struct option long_options[] = {
    {"aa", no_argument,  0,  'a' },
    {"bb", no_argument,  0,  'b' },
    {0,    0,            0,  0 }
};

int main (int argc, char **argv)
{
  int c;
  int option_index;

    opterr = 0;
    while ((c = getopt_long (argc, argv, "ab",
                    long_options, &option_index)) != -1)
        switch (c) {
            case 0:
                printf ("option %s", long_options[option_index].name);
                if (optarg)
                    printf (" with arg %s", optarg);
                printf ("\n");
                break;
            case 'a':
                printf("got option a\n");
                break;
            case 'b':
                printf("got option b\n");
                break;
            case '?':
                if (isprint (optopt))
                    printf ("Unknown option `-%c'.\n", optopt);
                else
                    printf ("Unknown option character `\\x%x'.\n", optopt);
                return 1;
            default:
                printf("?? getopt_long returned character code 0%o ??\n", c);
                return 1;
        }
    if (optind < argc) {
        printf("non-option ARGV-elements: ");
        while (optind < argc)
            printf("%s ", argv[optind++]);
        printf("\n");
    }
    return 0;
}

这里是运行:

$ ./a.exe -ab --aa --bb # works correctly
    got option a
    got option b
    got option a
    got option b
$ ./a.exe -z      # prints error message correctly
    Unknown option `-z'.
$ ./a.exe --zz    # not getting the error message for "--zz"
    Unknown option character `\x0'.

如何打印 --zz 是未知选项的错误消息?

【问题讨论】:

  • 根据man getopt_long,这是未知长选项的预期行为。

标签: c++ getopt getopt-long


【解决方案1】:

在这种情况下,我使用了 optind 在指向失败的选项后刚刚递增的事实来发现原始 argv 中的选项。

所以我会这样做:

case '?':
    std::cerr << "Unknown option " << argv[optind - 1] << ".\n";
    return EXIT_FAILURE;

没有必要以这种方式区分多头和空头期权。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-11-03
    • 2015-06-14
    • 2013-11-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多