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.

Recommended Answers

All 2 Replies

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

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.