3

I have a program that takes a few options and I want to recognize when no argument is provided.

This is what happen when I call my program without one option arg

program -lib

cout: the required argument for option '-lib' is missing

That's ok, but when I call my program with additional options, e.g

program -lib -out number

The variable assigned to lib gets the value "-out", although -out was declared as an option. I expect to get the same warning as in the first example.

I can solve this problem by adding a custom notifier to all the options, code below:

void validate_string(const std::string& r)
{
    if (*r.begin() == '-') { 
            throw Something
    }
}

...

("lib", po::value<std::string>(&lib)->notifier(validate_string), "Library")

There's any way of doing this with a build-in mechanism of boost::program_options? I don't like my current solution, the options declaration look messy and is hard to read. Besides -out is not getting assigned.

BTW: I'm using allow_long_disguise, so single - is allowed for long options

dlavila
  • 1,204
  • 11
  • 25
  • Your keyword is bool_switch, see the possible duplicate: http://stackoverflow.com/questions/23703890/how-to-use-boostprogram-options-to-accept-an-optional-flag – DarthB May 06 '15 at 15:53
  • no, bool_switch is for flags that don't take args, my options take args – dlavila May 06 '15 at 16:21
  • Weirdly enough the behaviour is the one you want for short options: `program -lib -o number` gives you your warning. – Drax May 06 '15 at 16:37
  • Well my bad! You may achieve your favored result by changing the style_t enum of your parser object using: po::command_line_parser::style() method. It seems like your current parser uses the following style_option: short_allow_next = short_allow_adjacent << 1, Hopefully that will help you – DarthB May 06 '15 at 16:43
  • @Drax they are long options, I use `allow_long_disguise` – dlavila May 06 '15 at 16:49
  • @dlavila I know i was just pointing out that the behaviour you want works on short options and not on long ones – Drax May 06 '15 at 17:07
  • @Drax, I need that behaviour for long options, I can't change the API of my program – dlavila May 06 '15 at 17:09
  • I would like to point out that, `gcc main.c -o -O2` will create a _-O2_ binary without complaining (maybe there's just no way to know if the user forgot an argument or wanted it just like this) – Zermingore Jan 21 '16 at 13:02

0 Answers0