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.

5 Years
Discussion Span
Last Post by vijayan121

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).

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.