gpt4 book ai didi

c++ - boost::program_options 总是用空值解析命令行

转载 作者:太空宇宙 更新时间:2023-11-04 12:52:19 25 4
gpt4 key购买 nike

在 debian stretch 和 gcc 6.4.0 上,boost 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。为什么??

最佳答案

我只能猜测您运行的二进制文件有误。

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

关于c++ - boost::program_options 总是用空值解析命令行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48436551/

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