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?
我想为我的一些命令行参数使用默认值。如何告诉program_options默认选项是什么,如果用户不提供参数,如何告诉我的程序使用默认值?
Say I want to have an argument specifying the number of robots to send on a murderous rampage with a default value of 3.
假设我想要一个参数来指定在杀人狂暴中发送的机器人数量,默认值为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
.
机器人技能 - 机器人5将产生5个机器人已开始硅革命,而机器人技能(没有提供参数)将产生3个机器人已开始硅革命。
1 个解决方案
#1
20
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.
当用户不提供这些选项时,program_options会自动为选项分配默认值。您甚至不需要检查用户是否提供了给定选项,在任何一种情况下都只使用相同的分配。
#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;
}
#1
20
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.
当用户不提供这些选项时,program_options会自动为选项分配默认值。您甚至不需要检查用户是否提供了给定选项,在任何一种情况下都只使用相同的分配。
#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;
}