【问题标题】:Print default argument when using getopt in C++在 C++ 中使用 getopt 时打印默认参数
【发布时间】:2018-01-03 17:16:00
【问题描述】:
static struct option long_options[] =
{
     {"r",   required_argument,  0, 'r'},
     {"help",        no_argument,        0, 'h'},
     {0, 0, 0, 0}
};


int option_index = 0;
char c;
while((c = getopt_long(argc, argv, "r:h", long_options, &option_index)) != -1)
{
    switch(c)
    {
        case 'r':
            break;
        case 'h':
            return EXIT_SUCCESS;
    }
}

如何让 h 成为默认参数,所以如果这个程序在没有任何参数的情况下运行,就好像它是用 -h 运行的一样?

【问题讨论】:

    标签: c++ arguments command-line-arguments getopt getopt-long


    【解决方案1】:

    也许可以试试这样的:

    static struct option long_options[] =
    {
         {"r",    required_argument,  0, 'r'},
         {"help", no_argument,        0, 'h'},
         {0, 0, 0, 0}
    };
    
    int option_index = 0;
    char c = getopt_long(argc, argv, "r:h", long_options, &option_index);
    if (c == -1)
    {
        // display help...
        return EXIT_SUCCESS;
    }
    
    do
    {
        switch(c)
        {
            case 'r':
                break;
    
            case 'h':
            {
                // display help...
                return EXIT_SUCCESS;
            }
        }
    
        c = getopt_long(argc, argv, "r:h", long_options, &option_index);
    }
    while (c != -1);
    

    或者这个:

    static struct option long_options[] =
    {
         {"r",    required_argument,  0, 'r'},
         {"help", no_argument,        0, 'h'},
         {0, 0, 0, 0}
    };
    
    int option_index = 0;
    char c = getopt_long(argc, argv, "r:h", long_options, &option_index);
    if (c == -1)
        c = 'h';
    
    do
    {
        switch(c)
        {
            case 'r':
                break;
    
            case 'h':
            {
                // display help...
                return EXIT_SUCCESS;
            }
        }
    
        c = getopt_long(argc, argv, "r:h", long_options, &option_index);
    }
    while (c != -1);
    

    【讨论】:

      【解决方案2】:

      为什么不创建一个 printUsage 函数并执行类似的操作。

      if (c == 0) {
          printUsage();
          exit(-1);
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-09-28
        • 2020-02-05
        • 2023-03-07
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2010-11-15
        • 1970-01-01
        相关资源
        最近更新 更多