Other One-Parameter Output Stream Manipulators

You can create manipulators that take arguments other than int and long. In addition to the OMANIP macro, you must use the IOMANIPdeclare macro, which declares the classes for your new type.

Example 2

Example 2 uses a class money, which is a thinly disguised long type. A new manipulator, setpic, attaches a formatting “picture” string to the class that can be used by the overloaded stream insertion operator of the class money. Note that the picture string is stored as a static variable in the money class rather than as data member of a stream class. This means you do not have to derive a new output stream class.

// exios202.cpp

// A custom manipulator with a char* parameter

#include <iostream.h>

#include <iomanip.h>

#include <string.h>

typedef char* charp;

IOMANIPdeclare( charp );

class money {

private:

long value;

static char *szCurrentPic;

public:

money( long val ) { value = val; }

friend ostream& operator << ( ostream& os, money m ) {

// A more complete function would merge the picture

// with the value rather than simply appending it

os << m.value << '[' << money::szCurrentPic << ']';

return os;

}

friend ostream& setpic( ostream& os, char* szPic ) {

money::szCurrentPic = new char[strlen( szPic ) + 1];

strcpy( money::szCurrentPic, szPic );

return os;

}

};

char *money::szCurrentPic; // Static pointer to picture

OMANIP(charp) setpic(charp c)

{

return OMANIP(charp) (setpic, c);

}

void main()

{

money amt = 35235.22;

cout << setiosflags( ios::fixed );

cout << setpic( "###,###,###.##" ) << "amount = " << amt << endl;

}