Click here to Skip to main content
Click here to Skip to main content

CGetOpt - A commandline Parameter Parsing Class

, 6 Mar 2006
Rate this:
Please Sign up or sign in to vote.
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

Name Value Type
-booltest 1 boolean
-url www.url-check.com string
-log - -
-check true boolean

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:

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

For example, three parameters are added:

Name Type
-booltest boolean
-url string
-log -
-check boolean
// 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 Type Description
WrongTypeException Wrong parameter type is used
ValueExpectedException Value was expected, but none was given
UnknownParameterException Unknown parameters are used
DoubleParametersException Parameters are used twice

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

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?

    ParameterUsed(string sParameter);

    Get the value of the parameter:

    Param oInfo = GetParameterResultInfo(string sParameter);
    printf("%s => %s\n", oInfo.sParameter.c_str(), oInfo.sValue.c_str());
  2. Iterate through all the used items:
    // 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)

About the Author

Geert van Horrik
Software Developer CatenaLogic
Netherlands Netherlands
I am Geert van Horrik, and I have studied Computer Science in the Netherlands.
 
I love to write software using .NET (especially the combination of WPF and C#). I am also the lead developer of Catel, an open-source application development framework for WPF, Silverlight, WP7 and WinRT with the focus on MVVM.
 
I have my own company since January 1st 2007, called CatenaLogic. This company develops commercial and non-commercial software.
 
To download (or buy) applications I have written, visit my website: http://www.catenalogic.com
Follow on   Twitter

Comments and Discussions

 
GeneralBoost.Program_Options PinmemberÉric Malenfant7-Mar-06 3:19 
GeneralRe: Boost.Program_Options PinmemberGeert van Horrik7-Mar-06 4:31 
GeneralRe: Boost.Program_Options PinmemberÉric Malenfant7-Mar-06 6:09 

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

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

| Advertise | Privacy | Mobile
Web01 | 2.8.140709.1 | Last Updated 7 Mar 2006
Article Copyright 2006 by Geert van Horrik
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid