C++ Tutorial: User Defined Manipulators

In C++, user can define and use manipulator similar to built in manipulators as per the users’ used and desire to control the format of input and output. Similar to the predefined built manipulators use can define non parameterized as well as parameterized manipulators. The syntax for designing manipulator is as follows:

 

ostream& manipulator_name(ostream& output, args..){
//body of user defined manipulators
return output;
}

The manipulator_name is the name of the user defined manipulator, ostream & ouput is the manipulator called and stream cascading object and args is the number of arguments for parameterized manipulators. The following example illustrates how to use parameterized custom manipulator.

#include<iostream>

#include<cstring>


using std::cin;

using std::cout;

using std::endl;

using std::ostream;

using std::flush;


class UD_Manip

{

private:

int width, precision;

char fill;

public:

UD_Manip(int W, int P, char F){

width = W;

precision = P;

fill = F;

}

friend ostream& operator<<(ostream&, UD_Manip);

};


ostream& operator <<(ostream& out, UD_Manip manip)

{



out.width(manip.width);

out.precision(manip.precision);

out.fill(manip.fill);

out<<flush;

return out;

}



UD_Manip setwpf (int w, int p , char f)

{

return UD_Manip(w, p, f);


}


int main()

{

cout<<setwpf(10,5,'#')<<28.66565544;

return 0;

}
SHARE C++ Tutorial: User Defined Manipulators

You may also like...

2 Responses

  1. Anonymous says:

    Much simpler in C++11 :

    #include
    #include

    using namespace std;

    ostream& operator <<(ostream& out, tuple manip)
    {
    out.width(get<0>(manip));
    out.precision(get<1>(manip));
    out.fill(get<2>(manip));
    out< setwpf (int w, int p, char f)
    {
    return tuple(w,p,f);
    }

    int main()
    {
    cout << setwpf(10,5,'#') << 28.66565544;
    }

  2. Ohh i will check it out….

Leave a Reply

Your email address will not be published.

Share