gpt4 book ai didi

c++ - boost program_options 一起解析选项和参数

转载 作者:行者123 更新时间:2023-11-30 05:49:09 26 4
gpt4 key购买 nike

#include <boost/program_options.hpp>

#include <iostream>
#include <string>
#include <stdexcept>


void basic_approach(int argc, char const *argv[])
{
try
{
options_description desc{"Options"};
desc.add_options()
("help,h", "Help screen")
("pi,p", value<float>()->default_value(3.14f), "Pi")
("bool,b", value<bool>()->default_value(false), "bool");

variables_map vm;
store(parse_command_line(argc, argv, desc), vm);
notify(vm);


if (vm.count("help")){
std::cout << desc << '\n';
}
if (vm.count("pi")){
std::cout << "Pi: " << vm["pi"].as<float>() << '\n';
}
if(vm.count("bool")){
std::cout<<"bool: "<<vm["bool"].as<bool>() <<"\n";
}
}
catch (const error &ex)
{
std::cerr << ex.what() << '\n';
}
}

int main(int argc, char const *argv[])
{
basic_approach(argc, argv);
}

当我输入 "test.exe --pi 334" 时,程序运行完美。
但是它无法解析“test.exe --pi334”而是抛出异常

"unrecognised option '--pi334'"

boost是否可以解析像“--pi334”这样的选项?非常感谢

最佳答案

#include <boost/program_options.hpp>

#include <iostream>
#include <string>
#include <stdexcept>


void basic_approach(int argc, char const *argv[])
{
try
{
options_description desc{"Options"};
desc.add_options()
("help,h", "Help screen")
("pi,p", value<float>()->default_value(3.14f), "Pi")
("bool,b", value<bool>()->default_value(false), "bool");

command_line_parser parser(argc, argv);
parser.options(desc).style(
command_line_style::default_style |
command_line_style::allow_sticky);
parsed_options parsed_options = parser.run();

variables_map vm;
store(parsed_options, vm);
notify(vm);

if (vm.count("help")){
std::cout << desc << '\n';
}
if (vm.count("pi")){
std::cout << "Pi: " << vm["pi"].as<float>() << '\n';
}
if(vm.count("bool")){
std::cout<<"bool: "<<vm["bool"].as<bool>() <<"\n";
}
}
catch (const error &ex)
{
std::cerr << ex.what() << '\n';
}
}

int main(int argc, char const *argv[])
{
basic_approach(argc, argv);
}

感谢sehe的帮助,我只需要加上command_line_style::allow_sticky就可以了

关于c++ - boost program_options 一起解析选项和参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27898356/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com