1

This is my code:

#include <iostream>
#include <string>
#include "boost/program_options.hpp"
namespace po = boost::program_options;

int main(int argc, char *argv[]) {
    po::options_description cli_opts_desc("General flags");
    cli_opts_desc.add_options()
        ("help,h", po::value<std::string>()->default_value("all"), "Show this help message.")
    ;
    po::variables_map flags;
    po::store(po::parse_command_line(argc, argv, cli_opts_desc), flags);
    if (flags.count("help")) {
        std::cout << "flags['help'] is " << flags["help"].as<std::string>() << std::endl;
        if (flags["help"].as<std::string>() != "all") std::cout << "specific description for "
                                                              << flags["help"].as<std::string>() << std::endl;//todo
        else std::cout << cli_opts_desc << std::endl;
    } else {
        std::cout << "no --help provided" << std::endl;
    }
}

Or rather, a simplified version of it. When I run

./test

it shows the help message, as expected. However, if I run

./test --help #or
./test -h

then it throws an error:

terminate called after throwing an instance of 'boost::exception_detail::clone_impl<boost::exception_detail::error_info_injector<boost::program_options::invalid_command_line_syntax> >'
  what():  the required argument for option '--help' is missing
Aborted

I don't understand why this is happening even when I declare a default value.

What's causing this error? How can I fix it?

NB: I'd like to avoid using implicit_value if possible; in the real world, this isn't limited to my --help, and being able to specify arguments to short options with a space between is a nice little thing that avoids stupid errors.

Nic
  • 6,211
  • 10
  • 46
  • 69
  • 1
    "default_value" means that the default value is used ONLY if you don't use this option (e.g. a pure './test'). However, if you use this option ('-h'), then you MUST add the default to the command line (e.g. './test -h foo'). That is how boost's program_options works. With other words: this behavior is intended. – mdew Nov 23 '16 at 10:37

1 Answers1

0

Try this:

("help,h", "Show this help message.")

No parameter, but no complaint when there is no parameter supplied.

madGambol
  • 15
  • 2