c++ - getopt_long 不打印错误消息

标签 c++ getopt getopt-long

我正在使用 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;

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

关于c++ - getopt_long 不打印错误消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48810683/

相关文章:

c++ - Firebreath 框架中的 FocusChanged 事件

C++ OpenCV 包含错误 'file not found'

c++ - WSACleanUp 导致异常

perl - 使用Getopt解析args时如何允许未定义的选项

C getopt_long 选项的两个必需参数

c# - 如何添加实现 C++ 接口(interface)的标签?

c - 使用命令行参数时出现段错误

C 使用 isdigit 检查 optarg 是否为数字

perl - 使用 Getopt::Long 为同一变量赋值

linux - 关闭 getopt_long (optarg.h) 中的缩写?