boost program_options一起解析选项和参数

时间:2015-01-12 09:01:38

标签: c++ boost

#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" 时,该程序可以正常运行 但它cannot parse "test.exe --pi334"但抛出异常

"unrecognised option '--pi334'"

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

1 个答案:

答案 0 :(得分:1)

#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一起使用