In this C++ tutorial, you will learn what a manipulator is, endl manipulator, setw manipulator, setfill manipulator and setprecision manipulator are all explained along with syntax and examples.
What is a Manipulator?
Manipulators are operators used in C++ for formatting output. The data is manipulated by the programmer’s choice of display.
There are numerous manipulators available in C++. Some of the more commonly used manipulators are provided here below:
endl Manipulator:
This manipulator has the same functionality as the ‘n’ newline character.
For example:
cout << "Exforsys" << endl;
cout << "Training";
produces the output:
Exforsys
Training
setw Manipulator:
This manipulator sets the minimum field width on output. The syntax is:
setw(x)
Here setw causes the number or string that follows it to be printed within a field of x characters wide and x is the argument set in setw manipulator. The header file that must be included while using setw manipulator is
#include <iostream>
using namespace std;
#include <iomanip>
void main( )
{
int x1=12345,x2= 23456, x3=7892;
cout << setw(8) << "Exforsys" << setw(20) << "Values" << endl
<< setw(8) << "E1234567" << setw(20)<< x1 << endl
<< setw(8) << "S1234567" << setw(20)<< x2 << endl
<< setw(8) << "A1234567" << setw(20)<< x3 << endl;
}
The output of the above example is:
setfill Manipulator:
This is used after setw manipulator. If a value does not entirely fill a field, then the character specified in the setfill argument of the manipulator is used for filling the fields.
The output of the above example is:
This is because the setw sets 10 for the width of the field and the number 50 has only 2 positions in it. So the remaining 8 positions are filled with $ symbol which is specified in the setfill argument.
setprecision Manipulator:
The setprecision Manipulator is used with floating point numbers. It is used to set the number of digits printed to the right of the decimal point. This may be used in two forms:
- fixed
- scientific
These two forms are used when the keywords fixed or scientific are appropriately used before the setprecision manipulator. The keyword fixed before the setprecision manipulator prints the floating point number in fixed notation. The keyword scientific, before the setprecision manipulator, prints the floating point number in scientific notation.
The output of the above example is:
The first cout statement contains fixed notation and the setprecision contains argument 3. This means that three digits after the decimal point and in fixed notation will output the first cout statement as 0.100. The second cout produces the output in scientific notation. The default value is used since no setprecision value is provided.