p-ranav / argparse

Argument Parser for Modern C++
MIT License
2.59k stars 244 forks source link

Arguments without value are allowed when default_value() is set #369

Closed tlemo closed 5 days ago

tlemo commented 1 month ago
  args.add_argument("--foo")
      .default_value(5)
      .scan<'i', int>();

If my reading of the documentation is correct, such an argument (which doesn't set the implicit value), should require an explicit value on the command line, or arguments parsing should fail. This is not the case with the latest release (3.0), where the argument parsing succeeds w/o an error (and an td::bad_any_cast exception would be thrown when we try to get the value with get<int>("--foo")).

Eng-MohamedHussien commented 3 weeks ago

Hi @tlemo,

Since the argument is actually optional, no error is thrown when running the program without --verbose. Note that by using .default_value(false), if the optional argument isn’t used, it's value is automatically set to false.

Eng-MohamedHussien commented 3 weeks ago

Test code

#include <argparse/argparse.hpp>

int main(int argc, char *argv[]) {
  argparse::ArgumentParser program("test");

  program.add_argument("--foo").default_value(5).scan<'i', int>();

  try {
    program.parse_args(argc, argv);
  }
  catch (const std::exception& err) {
    std::cerr << err.what() << std::endl;
    std::cerr << program;
    return 1;
  }

  auto input = program.get<int>("--foo");
  std::cout << input << std::endl;

  return 0;
}
Eng-MohamedHussien commented 3 weeks ago

Hi @p-ranav @tlemo, You can close the issue.