سؤال

I have a cfg file as the following:

parameter1="hello"
parameter2=22
parameter3=12

Using boost_program to read all the parameters works fine with this code:

po::options_description options("Options");
options.add_options()
  ("help,h", "produce help message")
  ("parameter1", po::value<string>(&parameter1)->default_value("bye"),
   "parameter1")
  ("parameter2", po::value<int>(&parameter2)->default_value(2),
   "parameter2")
  ("parameter3", po::value<int>(&parameter3)->default_value(4),
   "parameter3");


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

try
{
  po::store(po::parse_config_file< char >(filePath, options), vm);
}
catch (const std::exception& e)
{
  std::cerr << "Error parsing file: " << filePath << ": " << e.what() << std::endl;
}

...

But when I try to do a generic method where i just want to read one parameter given from a call, I have an error parsing.

I want to read the second parameter for instance, so I write this:

const char parameter_string = "parameter2";
int default = 30;
int parameter;
getparameter(parameter_string,parameter,default);

and goes to the method getsparameter where this is what I have this time: ...

po::options_description options("Options");
options.add_options()
  ("help,h", "produce help message")
  (parameter_string, po::value<int>(&parameter)->default_value(default),
   "reading parameter");

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

but the error is:

Error parsing file: file.cfg: unknown option parameter1

So my question is if it is posible to read only one parameter from a file or it is necessary to parse all the parameters with boost_program in options.add_option including as many lines as parameters I write in the config file and then take the value from the parameter I want.

هل كانت مفيدة؟

المحلول 2

As I an using "parse_config_file" I see in the documentation that "allow_unregistered" is set to false by default.

template<typename charT> 
  BOOST_PROGRAM_OPTIONS_DECL basic_parsed_options< charT > 
  parse_config_file(std::basic_istream< charT > &, 
                const options_description &, 
                bool allow_unregistered = false);

So i modified my line like this:

Old code:

po::store(po::parse_config_file< char >(filePath, options), vm);

New code:

po::store(po::parse_config_file< char >(filePath, options, true), vm);

And as I said, It works. Thank you for your answer.

نصائح أخرى

Use allow_unregistered function :

Specifies that unregistered options are allowed and should be passed though. For each command like token that looks like an option but does not contain a recognized name, an instance of basic_option will be added to result, with 'unrecognized' field set to 'true'. It's possible to collect all unrecognized options with the 'collect_unrecognized' funciton.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top