Documentation


argumentParserLine_test.cpp

This is an example of how to parse a command line.
/*
 Test program for the argumentParser class. This parser allows you to simply declare
the variables to parse by providing for each variable:
- a pointer to the variable;
- a short name (0 if no short name);
- a long name ("" if no long name);
- a comment, which is automatically displayed when using the help option  (-h or --help by default)

Two kinds of arguments can be defined:
- arguments are mandatory. A run-time error happens if a parameter is not given in the command line;
- options are not mandatory.

You can parse your own custom types, as long as they implement standard operators << and >>
An example is given in this program.
*/

#include <animal/argumentParser.h>

using std::istream;
using std::ostream;
using std::cout;
using std::cin;
using std::endl;

// ======== a custom type with ist input/output methods  ============
struct MyComplex {
    double real, imaginary;
    MyComplex( double r=0, double i=0 ): real(r), imaginary(i) {}
};

ostream& operator << ( ostream& str, const MyComplex& c ) {
    str << c.real << " " << c.imaginary;
    return str;
}

istream& operator >> ( istream& str, MyComplex& c ) {
    str >> c.real >> c.imaginary;
    return str;
}

// ======== the program ===============
main( int argc, char* argv[] ) 
{

//  variables and default values
double d=2.2;
int i=0;
MyComplex c;
bool f1=false;
bool f2=false;

// Define and parse command line arguments.
// By default, -h and --help are used for help.
animal::parse("This is a test program \
for the Argumentparser class. This parser allows you to easily parse a command \
line including short or long names for arguments. Short names start with prefix - and \
consist of one character. They can be concatenated, e.g. -ifd. Long names start with \
prefix -- and can not be concatenated.")
 .parameter( &d, 'd', "double", "what my double means" )
 .option(    &i, 0, "int", "what my integer means" )    // no short name for this one
 .parameter( &c, 'c', "", "what my complex means" )     // no long name for this one
 .option(    &f1, 'f', "flag1", "what my first flag means" )
 .option(    &f2, 'g', "flag2", "what my second flag means" )
 ( argc, argv ); 

// try the following command lines
// a.out -h
// a.out --int 6 
// a.out --int 6 -d 5.5 --cplx 1.2 3.4 
// a.out --flag1 --double 4.3  --int x -c 1.2 3.4
// a.out -fgd 7.3

cout << "d = " << d << endl;
cout << "i = " << i << endl;
cout << "c = " << c << endl;
if( f1 ) cout << "flag 1 is set" << endl;
if( f2 ) cout << "flag 2 is set" << endl;

}



Generated on Thu Dec 23 13:52:23 2004 by doxygen 1.3.6