How can I parse a command-line option in C++ if it includes an equal sign? An example would be:
./testApp --parameter1=value1
I use the following line to check if the argument does exist with:
bool cmdOptionExists(char** begin, char** end, const std::string& option)
{
return std::find(begin, end, option) != end;
}
However, if the argument includes an equal sign this will return false for
cmdOptionExists(argv, argv+argc, "parameter1");
Even printing:
for(int i=0;i<argc;i++)
printf("Argument: %s\n", argv[i]);
does not include any indication of parameter1. Yet, removing the equals sign will print it correctly.
You can parse them the same way you can parse anything else. In your
example,
argv[1]will probably contain"--parameter1=value1".[1] Soif you want to break it at the
'=', usestd::findto find the'=',and break it. I’d start by converting it to an
std::string, but thisisn’t really necessary. For a null terminated string like you find in
argv[i],argv[i]is the “begin” iterator, andargv[i] + strlen(is the “end” iterator.argv[i] )
[1] Formally, the standard really doesn’t say much about this, since it
all happens before anything in your program is executed. Practically,
however, the most common systems will allow the program which invokes
your program to pass in pretty much anything—even to
argv[0],which the standard does sort of specify. And all of the shells or
command processors I know will use white space to break up the command
line into words, in the absense of meta-characters. (What is considered
a meta-character, and how they are treated, varies greatly.)