Title: Easy Parsing of Command Line switches using STL
Author: Mohammed Lokhandwala
Email: <A href="mailto:email@example.com">firstname.lastname@example.org</A>
Environment: VC++ 5.0-6.0, NT 4.0, Win95/98
Keywords: Command Line, Parser, STL
Description: Describes how command line can be parsed using STL.
<!------------------------------- STEP 2 ---------------------------><!-- Include download and sample image information. -->
<!------------------------------- STEP 3 ---------------------------><!-- Add the article text. Please use simple formatting (
This article show code written using STL to parse the command line. It provides for three forms of command line parameter syntax. a) Pairs, which are of the form "/Name=Value" on the command line, b) Switch, which are of the form "/Value" on the command line, and finally c) Uninterpreted, which are of the form "Value" on the command line.
This class is designed for simplicity in use, as well as Windows style command line parameters. It is not highly customizable, except that it can be derived from, and all functions are therefore virtual. With minor modifications, it can be used with
WinMain, but my intention was to use it with standard
main argc, argv type parameters.
Using the code
This code is very simple to use. The full name of the only class is
Epoch::Foundation::CommandLineParser, for the rest of this article I will assume that the user is using the namespace. At a minimum, simply create an instance of the class
CommandLineParser, and then invoke the function
parse with the command line argument provided to main.
Then read values from it as follows.
In the above example, the parameter name is src. Blank is the default value, in case the user had not passed any value for that pair.
In addition, Programmers often expect a minimum set of parameters on the command line. If the minimum required parameters do not exist, the program typically terminates with a help screen. I have provided a function
verifyCompulsory, which accepts a list of compulsary pairs, switches, and uninterpreted data. Obviously, its really only useful for pairs, but for completeness, I have provided the facility to verify all three formats.
cerr << endl << "Invalid Parameters." << endl;
cerr << "Syntax: QUCL /src=\"source directory\" /dst=\"destination directory\" /versionize=true/false" << endl;
Points of Interest
As you will see in the implementation, I have used STL to implement the parser. It is really very simple use of STL, but nonetheless it contributes to making the code small and simple to implement.
This is the first version.