Syntax for creating user defined manipulators in C++

Syntax for creating user defined manipulators in C++

C++ provides a set of predefined manipulators. The header file iomanip.h header file contains these manipulators. Moreover, you can design your own manipulators in C++ to suit specific purpose. The user defined manipulators are defined as follows:

ostream & manipulator(ostream & ostr)
{
set of statements;
return ostr;
}

Consider the following example which creates a user defined manipulator named curr for displaying Rs. and sets the precision to 2.

#include <iostream.h>
#include <iomanip.h>

ostream & curr(ostream & ostr)
{
cout<< setprecision(2);
cout<<“Rs. “;
return ostr;
}

void main()
{
float amt = 4.5476;
cout<<curr<<amt;
}

//Output: Rs. 4.55