Reputation: 521
#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);
}
When I enter "test.exe --pi 334"
, the program work flawlessly.
But it cannot parse "test.exe --pi334"
but throw the exception
"unrecognised option '--pi334'"
Is it possible for boost to parse the option like "--pi334"? Thanks a lot
Upvotes: 1
Views: 100
Reputation: 521
#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);
}
Thanks for the help of sehe, I only need to and command_line_style::allow_sticky to make it work
Upvotes: 1