23

I want to use default values for some of my command line arguments. How do I tell program_options what the default option is, and, if the user doesn't supply the argument, how do I tell my program to use the default value?

Say I want to have an argument specifying the number of robots to send on a murderous rampage with a default value of 3.

robotkill --robots 5 would produce 5 robots have begun the silicon revolution, whereas robotkill (no arguments supplied) would produce 3 robots have begun the silicon revolution.

flies
  • 2,017
  • 2
  • 24
  • 37
  • 1
    The solution to this problem couldn't be simpler, but I couldn't find it documented anywhere, so I made this question. – flies Apr 17 '12 at 16:27
  • Related: how to tell if an option with a default value has been supplied by the user http://stackoverflow.com/questions/9200598/boost-program-options-with-default-values-always-present-when-using-vm-count (`count` doesn't work, apparently because even when the option is not supplied the variable map will assign the default value, so count is never zero) – flies Apr 17 '12 at 16:32
  • 1
    http://www.boost.org/doc/libs/1_65_1/doc/html/boost/program_options/typed_value.html#idp698602832-bb for the technical description and http://www.boost.org/doc/libs/1_65_0/doc/html/program_options/tutorial.html#idp419580960 for the relevant tutorial explanation. Admittedly, I had to hunt for those after using your answer to find the correct name to look for. – pattivacek Oct 18 '17 at 11:59

1 Answers1

29

program_options automatically assigns default values to options when the user doesn't supply those options. You don't even need to check whether the user supplied a given option, just use the same assignment in either case.

#include <iostream>
#include <boost/program_options.hpp>

namespace po = boost::program_options;

int main  (int argc, char* argv[]) {

  po::options_description desc("Usage");
  desc.add_options()
    ("robots", po::value<int>()->default_value(3), 
     "How many robots do you want to send on a murderous rampage?");

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

  try {
    po::notify(opts);
  } catch (std::exception& e) {
    std::cerr << "Error: " << e.what() << "\n";
    return 1;
  }

  int nRobots = opts["robots"].as<int>(); 
  // automatically assigns default when option not supplied by user!!

  std::cout << nRobots << " robots have begun the silicon revolution" 
        << std::endl;
  return 0;
}
João Portela
  • 6,338
  • 7
  • 38
  • 51
flies
  • 2,017
  • 2
  • 24
  • 37