gpt4 book ai didi

c++ - 如何使用 Boost.program_options 检测拼写错误?

转载 作者:可可西里 更新时间:2023-11-01 18:36:16 30 4
gpt4 key购买 nike

我使用 boost.program_options 库。考虑这个简化的案例。

po::options_description desc("Usage");
desc.add_options()
("uninstall,u", "uninstall program")
("custom,c", po::wvalue<std::wstring>(), "specify custom action");

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

我想在这样的命令行上产生错误:

testprog.exe -u c- action1

请注意,用户打错了“c-”而不是“-c”。但是解析器将其理解为单个 -u 选项。我该如何处理这种情况?

最佳答案

I want to produce error on such command-line:

testprog.exe -u c- action1

Note, user made a typo "c-" instead of "-c". But the parser understands this as a single -u option. How do I handle such cases?

指示 program_options 库不接受任何位置参数,您将获得所需的行为

编码&编译:

macmini:stackoverflow samm$ cat po.cc
#include <boost/program_options.hpp>
#include <boost/version.hpp>

#include <iostream>

int
main(int argc, char* argv[])
{
namespace po = boost::program_options;
po::options_description desc("Usage");
desc.add_options()
("uninstall,u", "uninstall program")
("custom,c", po::wvalue<std::wstring>(), "specify custom action")
;

po::variables_map vm;
po::command_line_parser cmd_line( argc, argv );
cmd_line.options( desc );
cmd_line.positional( po::positional_options_description() );

try {
po::store( cmd_line.run(), vm );

po::notify(vm);
} catch ( const std::exception& e ) {
std::cerr << e.what() << std::endl;
return -1;
}

return 0;
}
macmini:stackoverflow samm$ g++ po.cc -I /opt/local/include -L/opt/local/lib -lboost_program_options -Wl,-rpath,/opt/local/lib

运行:

macmini:stackoverflow samm$ ./a.out -u c- action1
too many positional options
macmini:stackoverflow samm$ ./a.out -u -c action1
macmini:stackoverflow samm$

关于c++ - 如何使用 Boost.program_options 检测拼写错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7888211/

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