boost::program_options: how to ignore unknown parameters?
Asked Answered
F

2

11

In the boost::program_options library, I cannot understand how to allow the user to pass a parameter which has not been added through add_options().
I would like it to be just ignored, instead of terminating the program.

Faires answered 21/3, 2013 at 15:55 Comment(0)
H
15

I ran into this exact same problem tonight. @TAS's answer put me on the right path, but it still took 20 minutes of finger-mumbling to figure out the exact syntax for my particular use case.

To ignore unknown options, instead of writing this:

po::variables_map vm;
po::store(po::parse_command_line(argc, argv, desc), vm);
po::notify(vm);

I wrote this:

po::variables_map vm;
po::store(po::command_line_parser(argc, argv).options(desc).allow_unregistered().run(), vm);
po::notify(vm);

Note that only the middle line is different.

In a nutshell, use commandline_parser() rather than parse_commandline(), with some 'dangly bits' (i.e., .options(desc).allow_unregistered().run()) tacked on after the invocation.

Honea answered 23/3, 2016 at 2:56 Comment(0)
W
12

From the boost::program_options documentation How To: Allowing Unknown Options

parsed_options parsed = 
    command_line_parser(argc, argv).options(desc).allow_unregistered().run();      
Wenonawenonah answered 21/3, 2013 at 18:22 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.