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
.
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.
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.
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; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With