In the previous post, we had shown how basic input/output is performed in C++. Along with input/output operators, C++ provides a facility to control how the output is displayed on the screen. This is done using manipulators.
Let us understand what manipulators are.
- Manipulators are functions that are used to format or modify the output stream in various ways.
- They have a special characteristic that they are used along with insertion (<<) operator to change the format of the data.
- There are many manipulators in C++. But as of now, we will be dealing only with the endl and setw manipulators.
- To be able to use manipulators in our program, we must include <iomanip> header file in our source program.
- But here is an exception – the endl manipulator can be used without including the <iomanip> file.
Now let us see how these two manipulators work.
The endl manipulator works the same way as the ‘\n’ character in C++. That is the endl manipulator outputs the subsequent data or text in the next line.
But the difference is that endl also flushes the output buffer when it is used in a program.
Here is a sample program that shows how endl works.
using namespace std;
cout<<"Enter your roll number: ";
cout<<"Hello roll number "<<num<<endl;
cout<<"Welcome to your new class!!";
In the above program, endl operator is used in the fourth statement inside main() function.
After this statement, the string “Welcome to your new class!!” is printed in the next line on the output screen.
Here’s a live preview of the program and its output.
2. setw manipulator
This manipulator is used to set the width of the output in a program. It takes up an argument ‘n’ which is the width of the field in which the output is to be displayed.
By default, the output in the field is right-aligned.
Here is a sample program to show how it works.
using namespace std;
cout<<"Enter three numbers:\n";
cout<<"\nDisplaying the three numbers\n"
In the program above, we ask the user to input three integers and then we display them using setw() manipulator.
Notice how we have cascaded the ‘<<‘ operator to display the three numbers. We could have used individual cout statements for displaying each number.
Here is a live preview of this program along with its output. We can see how each of the three numbers is right aligned in a field width of size 8.
Try to run the same program without using the setw manipulator and see the difference in the output.
Hope you are clear with how these two manipulators work. Let us know your queries in comments below.