How do I get default argument values with boost program options?

flies picture flies · Apr 17, 2012 · Viewed 15.7k times · Source

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.

Answer

flies picture flies · Apr 17, 2012

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;
}