Sandro Lampart Sandro Lampart - 3 months ago 19
C++ Question

c++ 11 command line parameter separation

I'm pretty new to c++11 and I don't really get it how the command line arguments are parsed into the argv-pointer...

I have this code:

int main(int argc, char* argv[])
{
std::string curr_arg = "";

std::string str_base = "";
std::string str_subs_file = "";
std::string str_subs = "";

for(int i = 1; i < argc; i++)
{
curr_arg = argv[i];

if(curr_arg == "-b" || curr_arg == "--base")
{
str_base = argv[++i];
}
else if(curr_arg == "-f" || curr_arg == "--file")
{
str_subs_file = argv[++i];
}
else if(curr_arg == "-s" || curr_arg == "--subs")
{
str_subs = argv[++i];
}
else
{
std::cout << "Argument '" << argv[i] << "' is not recognised." << std::endl;
return -1;
}
}
}


When I call my program with ./subs -b base -s a=1,2,3;b=4,5,6;c=6,7,8 I would expect that I get "a=1,2,3;b=4,5,6;c=6,7,8" as argument when I enter in the
if(curr_arg == "-s" || curr_arg == "--subs"
block instead I just receive "a=1,2,3" and nothing more.
I know it works if I use quotes around the whole argument, but I don't understand why it happen like that..
Is there someone who can explain it to me?

Answer

You are not facing a problem with C++ but with your command shell. It is most probably because your shell takes the semicolon as a command seperator.

Your shell interprets your command as ./subs -b base -s a=1,2,3, then it detects the semicolon and interprets the next command, which is b=4,5,6 in your case and the same with c=6,7,8.

It is pretty much the same as typing (Which should work on most Unix shells):

echo abc; sleep 5; echo def 5 seconds later

This prints "abc", sleeps for 5 seconds and prints "def 5 seconds later" afterwards.

Solution: To get what you want, you could encapsulate the part a=1,2,3;b=4,5,6;c=6,7,8 with quotation marks like:

./subs -b base -s "a=1,2,3;b=4,5,6;c=6,7,8"

or you could escape the semicolon like:

./subs -b base -s a=1,2,3\;b=4,5,6\;c=6,7,8

Both versions should work with most (if not all) Unix shells and also in the windows cmd, I think.

Comments