0

I want to store a command line value into a variable. Here's my complete code:

#include <iostream>
#include <boost/program_options.hpp>

int main(int argc, char *argv[]) {
  int nselect = 100;
  boost::program_options::options_description desc("Allowed options");
  desc.add_options()
        ("help,h", "print usage message")
        ("nselect,N", boost::program_options::value<int>(&nselect), "number to select");
  boost::program_options::variables_map vm;
  boost::program_options::store(boost::program_options::parse_command_line(argc, argv, desc), vm);

  if (vm.count("help")) {
      std::cout << desc << "\n";
      return 0;
  }
  std::cout<<"nselect = "<<nselect<<"\n";
  return(0);
}

I compile it as g++ a.cpp -lboost_program_options, and then run:

$ ./a.out -N 5
nselect = 100

Why isn't it storing the command line value?

Resolution:

Calling notify(vm) automatically stores the value into the variable specified in the variable. Or one can map it from vm, as in the answer by @Matthieu-Brucher below.

highBandWidth
  • 16,751
  • 20
  • 84
  • 131

1 Answers1

1

I would actually do something different, more idiomatic for ProgramOptions:

namespace po = boost::program_options;

po::options_description desc("Options");
desc.add_options()
    ("help,h", "print usage message")
    ("nselect,N", po::value<int>()->default_value(100), "number to select");

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

int nselect = vm["nselect"].as<int>();

I didn't the notify call in your code, that may be the only thing to change, although I would go for the idiomatic way instead for readability.

Matthieu Brucher
  • 21,634
  • 7
  • 38
  • 62
  • Thanks! This can work. It's just that I would have to go over the list of all arguments first in the description and then in the vm. If I change one I have to change the other. It'd be nice to be ale to use the value() function too. – highBandWidth Jan 03 '19 at 17:29
  • Well, as it's stored in `vm`, you don't need to have a list of arguments somewhere else. I only have `nselect` in one place. – Matthieu Brucher Jan 03 '19 at 17:31
  • 1
    Actually, notify(vm) is what was missing in my code. It works after adding it. – highBandWidth Jan 03 '19 at 17:41
  • That was my thought as well. But still not very idiomatic, hence the suggestion. All the tutorials I've seen use this. – Matthieu Brucher Jan 03 '19 at 17:45
  • True, or a mixture of the two as in https://www.boost.org/doc/libs/1_55_0/libs/program_options/example/options_description.cpp – highBandWidth Jan 03 '19 at 17:50