p-ranav / argparse

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

Can the code parse arguments in format -key="some value with spaces" #338

Closed nikitin- closed 5 months ago

nikitin- commented 5 months ago

Hello!

Is it possible to setup the code of the parser to parse aguments in this format -key="some value with spaces"

e.g. '-key' is a parameter name '=' is a delimiter "some value with spaces" is a value (surrounded by doublequotes)

Thank you in advance

p-ranav commented 5 months ago

This almost works with program.set_prefix_chars and program.set_assign_chars.

I say almost because, for some reason in the past, argparse prefix chars was decided to be 2 characters long. I'll have to revisit that decision. But if you design it as a 2-character "long prefix", e.g., -D, it works. This was likely done to avoid some kind of ambiguity with parsing short optional arguments, e.g., -a.

foo:bar $ ./main -Dkey="some string with spaces"
Key: some string with spaces
#include "argparse.hpp"
#include <iostream>

std::string argname{"-Dkey"};

int main(int argc, char* argv[]) {

  argparse::ArgumentParser program("test");

  program.set_prefix_chars("-D");
  program.set_assign_chars("=");

  program.add_argument(argname);

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

  if (program.is_used(argname)) {
    std::cout << "Key: " << program.get(argname) << std::endl;
  }

}
nikitin- commented 5 months ago

@p-ranav - Thank you for reply and sorry for late response. I got the idea of "--key=" and "-key=" difference and adopted my portion of code for using "--key=".

p-ranav commented 5 months ago

Okay! Sounds good! Closing this.