Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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.

like image 557
flies Avatar asked Apr 17 '12 16:04

flies


People also ask

What are the default arguments and explain with a suitable examples?

Default arguments are overwritten when the calling function provides values for them. For example, calling the function sum(10, 15, 25, 30) overwrites the values of z and w to 25 and 30 respectively.

What is Boost program options?

Boost. ProgramOptions is a library that makes it easy to parse command-line options, for example, for console applications. If you develop applications with a graphical user interface, command-line options are usually not important. To parse command-line options with Boost.


1 Answers

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; } 
like image 93
2 revs, 2 users 98% Avatar answered Sep 17 '22 14:09

2 revs, 2 users 98%