In C++, how to use only long options with a required argument?

倾然丶 夕夏残阳落幕 提交于 2019-12-04 07:02:21

There are two problems:

  1. According to the example code (your link), the final option defined in the struct must be {0,0,0,0}. I recommend changing the definition to

    static struct option long_options[] =
      {
        {"help", no_argument, 0, 'h'},
        {"verbose", required_argument, 0, 'v'},
        {"param", required_argument, 0, 0},
        {0,0,0,0}
      };
    
  2. (And more importantly,) you must include code that actually processes the "param" option. You do that in the '0' case:

    case 0:
      if (long_options[option_index].flag != 0)
        break;
      if (strcmp(long_options[option_index].name,"param") == 0)
        param = atoi(optarg);
      break;
    

As you can see I use the strcmp function to compare the strings; for that you need to #include <cstring>. By the way, you also need #include <cstdio> for your use of printf.

With these changes in place, the program worked correctly for me (tested on GCC 4.5.1).

In your case statement, you are using:

case 'param':

which is giving you the warning, because compiler expects a single character in that place.

In fact, I realized that I should check the value of option_index when c has the value 0, like this. Such a case is not in the GNU libc examples, so here it is:

switch (c)
{
case 0:
  if (long_options[option_index].flag != 0)
    break;
  if (option_index == 2)
  {
    param = atoi(optarg);
    break;
  }
case 'h':
  help (argv);
  exit (0);
case 'v':
  verbose = atoi(optarg);
  break;
case '?':
  abort ();
default:
  abort ();
}

Another solution is to use 'flag' member value defined in struct option.

Setup your options like below:

int param_flag = 0;

{"param", required_argument, &param_flag, 1}

Then;

case 0:
    if (param_flag == 1) {
        do_something;
    }

See man getopt_long for details about struct option.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!