Monday 10 September 2012

C++ ( Tutorial IV )

Creating New Manipulators (Custom Manipulators)

You can create your manipulators to work along with ‘cout’ (output stream object) or with ‘cin’ (input stream object). Let us consider an example of a manipulator dealing with ‘cout’. The syntax for creating a manipulator is:

ostream& name (ostream &str)
{
//code to be executed;
}


In the case of manipulators to be used with input stream, only one modification is necessary.
 

istream& name (istream &str)
{
//code to be executed;
}


#include <iostream.h>
ostream& divider (ostream &str)
{
str<<"--------------------------------"<<endl;
return str;
}
int main( )
{
int x;
cout<<divider<<"Enter an integer value : ";
cin>>x;
cout<<divider<<"The value you entered is : ";
cout<<x;
return 0;
}


The output is:

--------------------------------
Enter an integer value : 98
--------------------------------
The value you entered is : 98

0 comments:

Post a Comment