argparse icon indicating copy to clipboard operation
argparse copied to clipboard

Arguments without value are allowed when default_value() is set

Open tlemo opened this issue 1 year ago • 3 comments
trafficstars

  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")).

tlemo avatar Jul 17 '24 20:07 tlemo

Hi @tlemo,

  • Issue is not reproducible (Env: used argparse version is 3.0 & GCC 13.2.0).
  • You have an issue in understanding how optional arguments is working.
  • Let's describe your doubt step by step:
  1. --foo means it's optional argument. Kindly check this section.
  2. default_value(5) it solved issue your talking about.

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 avatar Aug 16 '24 16:08 Eng-MohamedHussien

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 avatar Aug 16 '24 16:08 Eng-MohamedHussien

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

Eng-MohamedHussien avatar Aug 16 '24 16:08 Eng-MohamedHussien