vietjtnguyen / argagg

A simple C++11 command line argument parser
MIT License
224 stars 28 forks source link

bool argument #34

Closed maidekaraduman closed 2 years ago

maidekaraduman commented 2 years ago

how can i take a bool argument from cli ? for example i want to run my program like writing ./CLParser --size 2 --num 1 --istrue false or ./CLParser --size 2 --num 1 --istrue if i dont write nothing it takes true as default value

vietjtnguyen commented 2 years ago

If the argument is taking a boolean I think the idiomatic thing is to turn it into a flag instead of an option that takes an argument. If it takes an argument there must be a default unless you enforce that it is a required option (by returning failure when the option is not present).

So assuming the property at hand is named something like "with feature x" and the default is false then one CLI design is to have a no-argument flag --with-feature-x or --enable-feature-x that when specified enables the feature and when not specified defaults to the feature being disabled.

const parser argparser {{
    {
      "help", {"-h", "--help"},
      "displays help information", 0},
    {
      "with-feature-x", {"--with-feature-x"},
      "runs with feature x enabled (default: disabled)", 0},
  }};
const argagg::parser_results args = argparser.parse(argc, argv);
const bool enable_feature_x = args.has_option("with-feature-x");

Alternatively if it is enabled by default you could instead introduct a no-argument flag --without-feature-x or --disable-feature-x.

const parser argparser {{
    {
      "help", {"-h", "--help"},
      "displays help information", 0},
    {
      "disable-feature-x", {"--disable-feature-x"},
      "runs with feature x disabled (default: enabled)", 0},
  }};
const argagg::parser_results args = argparser.parse(argc, argv);
const bool enable_feature_x = not args.has_option("disable-feature-x");

If you still would rather take an argument to the option I would just use an integer argument and convert it to a bool.

const parser argparser {{
    {
      "help", {"-h", "--help"},
      "displays help information", 0},
    {
      "feature-x-enable-state", {"--feature-x-enable-state"},
      "sets whether feature x is enabled or disabled ", 1},
  }};
const argagg::parser_results args = argparser.parse(argc, argv);
if (not args["feature-x-enable-state"]) {
  std::cerr << "Option --feature-x-enable-state is required\n";
  return EXIT_FAILURE;
}
const bool enable_feature_x = (args["feature-x-enable-state"].as<int>() != 0);
maidekaraduman commented 2 years ago

thank you very much. it helped a lot :)