next up previous contents index Api Refernce
Next: 6.3 Error handling Up: 6.2 Calling functions Previous: 6.2.2 Calling member functions

6.2.3 Reading a user defined class at the command line

This chapter demonstrates how to read a class defined by the programmer at the command line.

A istream& operator >>(istream&, T&) is required for any class T to be read from the command line.

Imagine a class Attribute consisting of a key and a value - both of type string. The user should be able to enter them at the command line like:

% sample_prog -A myKey=myValue

All you have to do is to implement the class Attribute including an istream& operator >>(istream&, Attribute&). Then you call CmdLine::GetSingleValue giving the appropiate command line option string and a reference to an object of class Attribute. That's all.

A complete example looks like this:


#include <iostream>
#include <string>

#include "cmdline.h"

using namespace std;
using namespace cmdl; // defined in cmdline.h

//
// define a class 
//
class Attribute
{
public:
    Attribute(const char* szKey="", const char* szValue="")
      : m_strKey(szKey), m_strVal(szValue) { /* empty */ };

    const char* getKey() const { return m_strKey.c_str(); }
    const char* getVal() const { return m_strVal.c_str(); }

    void setKey(const char* szKey){ m_strKey = szKey; }
    void setVal(const char* szVal){ m_strVal = szVal; }

private:
    std::string m_strKey;
    std::string m_strVal;
};

//
// print an object to the screen (not needed for command line parameter evaluation)
//
ostream& operator <<(ostream& o, const Attribute & attr)
{
    o << "(key: \"" << attr.getKey() << "\" / value: \"" << attr.getVal() << "\")";
    return o;
}

//
// user defined operator >> - required by the cmdl-libary
//
istream& operator >>(istream& i, Attribute& attr)
{
    string strBuffer;
    i >> strBuffer;

    // key and value are seperated by a '='
    size_t pos = strBuffer.find('=');

    if (pos == string::npos)
    {  // no '=' => error 
	i.clear( ios::failbit ); // this causes a CmdLineException to be thrown, 
	                         // see the chapter about error handling.
    }
    else
    {  // seperate the string at the '='
       attr.setKey( strBuffer.substr( 0, pos ).c_str() );
       attr.setVal( strBuffer.substr( ++pos, string::npos ).c_str() );
    }

    return i;
}

//
// test it
//
int main(int argc, char* argv[])
{
    CmdLine C;
    C.Init( --check_argc, ++check_argv); // skip program name.

    // set a user defined type
    Attribute attr;
    if (C.GetSingleValue("-A", attr))
	cout << "Attribute (user type) set: " << attr << endl;

    // check if every option given was used. Unused options are unknown options!
    C.Done();
    
    return 0;
}



next up previous contents index Api Refernce
Next: 6.3 Error handling Up: 6.2 Calling functions Previous: 6.2.2 Calling member functions
Christian Neise
2003-01-12