Click here to Skip to main content
15,867,594 members
Articles / Programming Languages / C++

CGetOpt - A commandline Parameter Parsing Class

Rate me:
Please Sign up or sign in to vote.
4.72/5 (17 votes)
6 Mar 2006CPOL2 min read 53K   1.4K   46   7
This class enables you to easily parse a command line in any C++ application.
Sample Image - getopt_screen.png

Introduction

I needed a simple (but working) parameter parsing method. After searching for a long time, nothing came out. This doesn't mean there are no useful classes, but none of them fitted my needs. This class is able to parse all kinds of parameters.

For example, which classes are able to parse this:

Command Line Parameters

-booltest 1 -log -url www.url-check.com -check true

Parse Results

NameValueType
-booltest1boolean
-urlwww.url-check.comstring
-log--
-checktrueboolean

The main features are as follows:

  • No use of MFC, so the class can be used in Unix or Win32 applications
  • Type checking
  • Case sensitive or case insensitive, it’s adjustable
  • Uses exceptions instead of integer return values

This is not an award-winning piece of code. But, this piece of code will ease the pain when using parameters. So, if you are experiencing some problems when using parameters in your solutions, just try this class to see if it fits your requirements.

How to Use

This part will briefly explain how to use the CGetOpt class. If you still have any questions, just post your question in the forum below.

Start by adding these files to your project:

  • GetOpt.cpp
  • GetOpt.h

Adding Parameters

You have to add all the parameters the user can enter to the object. This allows the class to check for expected parameters, type checking and value checking. You can add a parameter to the class by calling the function:

C++
void AddExpectedParameter(string sParameter, bool bValueExpected = true, 
	ParameterType oParamType = PARAMETERTYPE_UNKNOWN);

For example, three parameters are added:

NameType
-booltestboolean
-urlstring
-log-
-checkboolean
C++
// Declare variables
CGetOpt oParamParsing;

// Add some example parameters
oParamParsing.AddExpectedParameter("-booltest", true, PARAMETERTYPE_BOOL);
oParamParsing.AddExpectedParameter("-url", true, PARAMETERTYPE_STRING);
oParamParsing.AddExpectedParameter("-log", false);
oParamParsing.AddExpectedParameter("-check", true, PARAMETERTYPE_BOOL);

All the parameters added to the CGetOpt object can now be used by the user.

Parsing

The parsing of the command line is very simple. The CGetOpt class uses different type of exceptions which can be caught.

The different exceptions that can be thrown are:

Exception TypeDescription
WrongTypeExceptionWrong parameter type is used
ValueExpectedExceptionValue was expected, but none was given
UnknownParameterExceptionUnknown parameters are used
DoubleParametersExceptionParameters are used twice

A simple example of parsing with error checking (all exceptions are caught):

C++
try
{
    // Parse parameters
    oParamParsing.ParseCommandLine(szCommandLine);
}
catch (exception & ex)
{
    printf("%s\n", ex.what());
}

Reading Parameter Results

There are two ways of reading the parameter results:

  1. Call all parameters by hand.

    Is parameter used?

    C++
    ParameterUsed(string sParameter);

    Get the value of the parameter:

    C++
    Param oInfo = GetParameterResultInfo(string sParameter);
    printf("%s => %s\n", oInfo.sParameter.c_str(), oInfo.sValue.c_str());
  2. Iterate through all the used items:
    C++
    // Show results
    for (int i = 0; i < oParamParsing.GetParameterResultCount(); i++)
    {
        Param oInfo = oParamParsing.GetParameterResultInfo(i);
        printf("%s => %s\n", oInfo.sParameter.c_str(), oInfo.sValue.c_str());
    }

CGetOpt Demo

There is also a small demo included. The demo contains the same code which is given as an example in this article.

The demo works quite simple. You start the application, four basic parameters are added to the allowed parameters, and you can try to enter a parameter list.

When you want to quit the demo application, simply hit enter with an empty line.

History

  • March 7th, 2006
    • Released version 1.1 which contains a small bug fix when checking for valid integer type
  • February 28th, 2006
    • Initial release

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer
Netherlands Netherlands
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
GeneralThanks Pin
Fastfootskater11-Jul-07 0:02
Fastfootskater11-Jul-07 0:02 
GeneralBoost.Program_Options Pin
Éric Malenfant7-Mar-06 3:19
Éric Malenfant7-Mar-06 3:19 
GeneralRe: Boost.Program_Options Pin
Geert van Horrik7-Mar-06 4:31
Geert van Horrik7-Mar-06 4:31 
GeneralRe: Boost.Program_Options Pin
Éric Malenfant7-Mar-06 6:09
Éric Malenfant7-Mar-06 6:09 
Good question. I don't know what impact it has on executable size.

Just for fun, I built the first example of the library's tutorial (http://www.boost.org/doc/html/program_options/tutorial.html#id2714212) The resulting executable size was 155kb. I then stripped the "program options" part, and only kept the "couts" at the end of main. The executable size was then at 95kb.

Of course, these numbers' scientific value is next to zero, but it may at least give you a rough idea.
GeneralFine! Pin
krause6-Mar-06 19:24
krause6-Mar-06 19:24 
GeneralRe: Fine! Pin
Geert van Horrik6-Mar-06 22:09
Geert van Horrik6-Mar-06 22:09 
GeneralThanks! Pin
Franklin van Velthuizen28-Feb-06 22:45
Franklin van Velthuizen28-Feb-06 22:45 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.