argparse
argparse copied to clipboard
Arguments without value are allowed when default_value() is set
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")).
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:
- --foo means it's optional argument. Kindly check this section.
- 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.
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;
}
Hi @p-ranav @tlemo, You can close the issue.