What is user defined manipulators? Illustrate with sample program.
Q.6) a)What is user defined manipulators? Illustrate with sample program.
Ans.
C++ provides many predefined manipulators but you can also create yourown manipulators. The syntax for creating user defined manipulators is defined as follows:
ostream&manipulator_name(ostream&ostrObj)
{
set of statements;
return ostrObj;
}
Example:
#include < iostream.h>
#include < iomanip.h>
ostream&curr(ostream&ostrObj)
{
cout << fixed << setprecision(2);
cout << "Rs.";
returnostrObj;
}
void main()
{
floatamt = 10.5478;
cout << curr << amt;
}
b) Explain any five manipulators with suitable example.
Ans.
Manipulators are special stream functions that are used to change certain characteristics of the input and output. Include < iomanip.h> header file for using these manipulators in your c++ program. The following are the list of important manipulator used in a C++.
- Endl
- hex, dec, oct
- setbase
- setw
- setfill
- setprecision
- ends
- ws
- flush
- setiosflags
- resetiosflags
endl : The endl is an output manipulator that is used to generate a carriage return. It works like ā\nā
Setbase() : The setbase() manipulator is used to convert the base of one numeric value into another base.
Setw () : It is used to specify the minimum number of character positions, a variable will consume on the command prompt.
The general syntax of the setw manipulator function is setw(int width )
Setfill() It is used to specify a different character to fill the unused space.
The general syntax of the setfill ( ) manipulator is setfill( char c)
Example:
setfill ( ā * ā ) / / fill an asterisk (*) character
setprecision(): Itis used with floating point numbers. You can set the number of digits printed to the right of the decimal point.
#include< iostream.h>
#include< iomanip.h>
void main (void)
{
int value;
float a,b,c;
a = 350;
b = 200;
c = a/b;
cout << " Enter number" << endl;
cin >> value;
cout << " Hexadecimal base =" << hex << value << endl;
cout << " Octal base =" << oct << value << endl;
cout << " hexadecimal base = " << setbase (16);
cout << value << endl;
cout << " Octal base = " << setbase (8) << value << endl;
cout << setfill ('*');
cout << setw (5) << a << setw (5) << b << endl;
cout << setw (6) << a << setw (6) << b << endl;
cout << setw (7) << a << setw (7) << b << endl;
cout << fixed << setprecision (2) << c << endl;
}
Output:
Enter number
100
Hexadecimal base =64
Octal base =144
hexadecimal base = 64
Octal base = 144
**350**200
***350***200
****350****200
1.75
Discussion
- RE: What is user defined manipulators? Illustrate with sample program. -vinay (08/05/16)
- Thanku for this information it is so use for me
- RE: What is user defined manipulators? Illustrate with sample program. -radhika (04/06/16)
- super