getopt_long没有打印错误信息

时间:2018-02-15 15:25:34

标签: c++ getopt getopt-long

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

以下是代码:

User       Event    Before   After
123          A      1        1
123          A      0        1
134          A      0        1

以下是运行:

#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;
}

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

1 个答案:

答案 0 :(得分:0)

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

所以我会做这样的事情:

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

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

相关问题