Documentation


argumentParserFile_test.cpp

This is an example of how to parse options and arguments from a file.
/*
 Test program for the argumentParser class applied to a file.
Provide the file name as argument.
*/

#include <animal/argumentParser.h>
using std::istream;
using std::ifstream;
using std::ostream;
using std::cout;
using std::cerr;
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;
}

main( int argc, char* argv[] ) 
{
if( argc<2 ){
    cerr<<"usage: cmdFile <file> [file...]"<<endl;
    exit(1);
}

// 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.
// -h and --help are reserved.
animal::ArgumentParser 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.");
parse
 .parameter( &d, 'd', "double", "what my double means" )
 .option(    &i, 0, "int", "what my integer means" )    // short names are not mandatory
 .parameter( &c, 'c', "cplx", "what my complex means" ) // neither are long names nor comments
 .option(    &f1, 'f', "flag1", "what my first flag means" )
 .option(    &f2, 'g', "flag2", "what my second flag means" );
for( int i=1; i<argc; ++i ){
    ifstream in(argv[i]);
    if( !in )
    {
        cerr << "Could not open file " << argv[i] << endl;
        exit(1);
    }
    parse( in ); 
}

/* write the following in a file, then parse the file
 -h
 --int 6 
 -d 5.5 --cplx 1.2 3.4 
 --flag1 --double r
 -fgi 7
*/

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