jarro2783 / cxxopts

Lightweight C++ command line option parser
MIT License
4.25k stars 590 forks source link

Throw exception in parse when there is no argument value for a positional option without default value #376

Open mrbeardad opened 2 years ago

mrbeardad commented 2 years ago

Current Behavior

  cxxopts::Options o{"", ""};
  o.add_options()("a", "", cxxopts::value<std::string>());
  o.parse_positional({"a"});
  std::vector<const char*> arg = {"a.out"};
  auto r = o.parse(arg.size(), arg.data());
  EXPECT_ANY_THROW(r["a"].as<std::string>());

Expected Behavior

  cxxopts::Options o{"", ""};
  o.add_options()("a", "", cxxopts::value<std::string>());
  o.parse_positional({"a"});
  std::vector<const char*> arg = {"a.out"};
  EXPECT_ANY_THROW(o.parse(arg.size(), arg.data()));
jarro2783 commented 2 years ago

I think that would be unintuitive for library users to have to catch that when a user doesn't type enough options. It gives more flexibility if library users have to check for the inputs, and allows some to still be left out. This request would make all positional options mandatory, which might not always be the case.

mrbeardad commented 2 years ago

If an option is optional, We can give it a default value.

  cxxopts::Options o{"", ""};
  o.add_options()("a", "", cxxopts::value<std::string>()->default_value("a"));
  o.parse_positional({"a"});
  std::vector<const char*> arg = {"a.out"};
  o.parse(arg.size(), arg.data());
  EXPECT_EQ(o["a"].as<std::string>(), "a");

To check whether a positional option is type by user, use o.count("a")