boost :: program_options解析命令行始终为空值

时间:2018-01-25 06:00:24

标签: c++ boost

关于debian伸展,gcc 6.4.0boost 1.66.0

boost::program_options解析命令行始终为空值。 以下代码:

#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <boost/filesystem.hpp>
#include <boost/program_options.hpp>

int main(int argc, char* argv[])
{
    using namespace boost::program_options;
    options_description desc{"Options"};
    desc.add_options()
            ("help,h", "Help screen")
            ("target,t", value<std::string>()->required(), "Set the target.");
    command_line_parser parser{argc, argv};
    parser.options(desc).allow_unregistered().style(command_line_style::default_style | command_line_style::allow_slash_for_short);
    parsed_options parsed_options = parser.run();
    variables_map vm;
    store(parsed_options, vm);
    notify(vm);
    if (vm.count("help"))
    {
        std::cout << desc << std::endl;
        return -1;
    }

    if (vm["target"].empty())
    {
        std::cout << "Error: empty" << std::endl;
        return -1;
    }

    if (vm.count("target"))
    {
        std::string target = vm["target"].as<std::string>();
        std::cout << target << std::endl;
        return -1;
    }
    return 0;
}

然后编译并运行。

./foo --target start

vm["target"].empty()始终是TRUE。为什么??

1 个答案:

答案 0 :(得分:0)

我只能猜测你运行的是错误的二进制文件。

<强> Live On Coliru

#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <boost/filesystem.hpp>
#include <boost/program_options.hpp>

int main(int argc, char* argv[])
{
    using namespace boost::program_options;
    options_description desc{"Options"};
    desc.add_options()
            ("help,h", "Help screen")
            ("target,t", value<std::string>()->required(), "Set the target.");

    command_line_parser parser{argc, argv};
    parser.options(desc).allow_unregistered().style(command_line_style::default_style | command_line_style::allow_slash_for_short);
    parsed_options parsed_options = parser.run();
    variables_map vm;
    store(parsed_options, vm);
    notify(vm);

    if (vm.count("help"))
    {
        std::cout << desc << std::endl;
        return -1;
    }

    if (vm["target"].empty())
    {
        std::cout << "Error: empty" << std::endl;
        return -1;
    }

    if (vm.count("target"))
    {
        std::string target = vm["target"].as<std::string>();
        std::cout << target << std::endl;
        return -1;
    }
    return 0;
}

./a.out --target HELLOWORLD的打印:

HELLOWORLD