getopt_long 不打印错误信息

getopt_long not printing error message

我正在使用 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 是未知选项的错误消息?

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

所以我会这样做:

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

这样就不用区分多头和空头了。