954,499 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

Command line parameter parsing

I want to parse command line arguments.

Say someone gives me

./progname param2 [-price=50] [-size=10] [-weight=16] [-height=7]

Square bracketed items are optional.

Either none or exactly two of -price, -size, -weight, and -height can be specified. If none of them are specified, it should be taking default values for price & weight.


I have already found how to decode for argv[0], argv[1].

But for argv[2] beyond till these optional items end, i am not able to parse.

I require code that can help me or some sort of syntax if complete code not possible. Thanks.

typedefcoder
Newbie Poster
4 posts since Nov 2011
Reputation Points: 10
Solved Threads: 0
 

Command-line argument handling is certainly a challenge, especially if you want to respond properly to mal-formed entries like "-option=val=somethingextra" or "-option =val" (note the embedded space). To start, assume the user will at least use correct arguments and formatting, so all you need to do is get the name and value.

Since you don't know which optional arguments you will get, you need to loop over the arguments you have:

for (int arg = 2;  arg < argc;  arg++) {
   ...
}

Inside that, for each argument, you need to determine which one it is. A simple strncmp() call will do that:

if (strncmp(argv[arg], "-price=", 7)) {
    ...
}
else if (...)


Then you need to extract the integer-value from the correct position in the string:

price = strtol(argv[arg] + 7);


And finally, it's useful to keep track of whether you saw that argument at all:

gotPrice = true;


This is a very C-centric approach (you could instead make a temporary std::string from the argument, find() the substring of interest and verify it's found at the start, create a strstream from it, and use the stream-input >>-operator to get the value), but should work with a minimum of fuss.

The rest of the logic should be easy enough to work out. The number of optional arguments is argc-2, again assuming no errors, and the user hasn't done something silly and specified the same argument twice (whether with the same value or different values).

raptr_dflo
Practically a Master Poster
602 posts since Aug 2010
Reputation Points: 76
Solved Threads: 82
 
vijayan121
Posting Virtuoso
1,606 posts since Dec 2006
Reputation Points: 1,159
Solved Threads: 287
 

This question has already been solved

Post: Markdown Syntax: Formatting Help
You
View similar articles that have also been tagged: