Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting command line options

Tags:

c++

I want to parse the command line options having specific format for getting the values. The function is as follows

char* getCmdOption(char** begin,
                    char** end,
                    const std::string& option)
{
   char** itr = std::find(begin, end, option);

  if (itr != end && ++itr != end)
  {
        return *itr;
  }
  return (char*)"";
}

The arguments passed are getCmdOption(argv, argv+argc, "--optionName") The code works fine for all the options and gives proper output but if I want to give values such as Application.exe --optionName surname="O Kief" the code should return me surname="O Kief" but instead it returns "surname=O Keif"

The format for input is Application.exe --optionName optionValue and expected output is "optionValue"

What is possibly wrong with the logic ? And how can i handle the case I have mentioned ?

like image 826
CMouse Avatar asked Mar 27 '26 23:03

CMouse


1 Answers

""is the only way to get the command interpreter (cmd.exe) to treat the whole double-quoted string as a single argument. Sadly, however, not only are the enclosing double-quotes retained (as usual) but so are the doubled escaped ones, so obtaining the intended string is a two-step process; e.g., assuming that the double-quoted string is passed as the 1st argument.

Application.exe --optionName option="name" removes the enclosing double-quotes then converts the doubled double-quotes to single ones. Be sure to use the enclosing double-quotes around the assignment parts to prevent unwanted interpretation of the values.

Although a precise solution is given below but you can visit this for in-depth solution of the problem (Not exactly a problem)

If the optionValue does not contain white spaces keep the format as

Application.exe --optionName "optionValue"

If the option Value contains white space wrap the thing in quote as

 Application.exe --optionName '"option Value"'
like image 62
CocoCrisp Avatar answered Mar 31 '26 03:03

CocoCrisp



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!