Wenn ich boost::program_options
benutze, nachdem validation_error
rausgeworfen wurde, zeigt die Fehlermeldung nicht den vollen Optionsnamen an.boost :: program_options: wie man validation_error mit dem vollständigen Optionsnamen und informativer macht
Ich habe den folgenden einfachen Beispielquellcode, kompiliert mit g++ -std=c++11 test.cpp -lboost_program_options
. Dieses Programm hat eine gültige Befehlszeilenoption: --hello-world
, die entweder auf a
oder b
, z. ./a.out --hello-world a
ist gültig, aber ./a.out --hello-world c
ist ungültig. Führen Sie dann den Code mit einer ungültigen Option aus, z. B. ./a.out --hello-world c
. Die Fehlermeldung lautet wie folgt aus:
the argument for option 'world' is invalid
Aber ich würde die Option Namen hello-world
und der ungültige Wert sollte auch angezeigt werden erwartet. Kann ich das irgendwie ändern?
#include <boost/program_options.hpp>
int main(int argc, const char** argv)
{
namespace po = boost::program_options;
char v;
po::options_description desc("Options");
desc.add_options()
("hello-world", po::value<>(&v)->default_value('a')->notifier(
[](char x)
{
if (x != 'a' && x != 'b')
throw po::validation_error(
po::validation_error::invalid_option_value,
"hello-world", std::string(1, x));
}),
"An option must be set to either 'a' or 'b'");
try
{
po::variables_map vm;
po::store(po::command_line_parser(argc, argv). options(desc).run(), vm);
po::notify(vm);
}
catch (const std::exception& e)
{
std::cerr << e.what() << std::endl;
return 1;
}
return 0;
}
Die offizielle Beispiel hier 'Input-file' verwendet einen Strich in seiner Optionsname: http://www.boost.org/doc/libs/1_63_0/ doc/html/programmoptionen/tutorial.html # idp523371328 – xuhdev