manipulators in c++ are

endl and setw manipulators in c++ show example

endl and setw manipulators in c++ : Are the operators use in the insertion operator(<<) to modify or manipulate the way data is displayed in I/O stream. The most commonly used manipulators are endl, setw, and setprecision. It is defined in the header file “iomanip.h” therefore we need to include it before using manipulators. The endl manipulator is also defined in iostream.h so if we want to use only “endl”,we don’t need to include “iomanip.h”.

what is endl manipulator? show its example

This causes a linefeed to be inserted into the output stream. It has the same effect as using the new line character ‘\n’. for example, the statement are as below:

cout<<“first value =”<<first<<endl<<“second value =”<<second;

will cause two lines of output.

“endl” is different from new line character ‘\n’ in the sense that it causes output buffer to be clear after the content is display in the monitor what left the output buffer on Clear due to which we need to clear the buffer by using or instructions.

what is setw manipulator? show its example

This manipulator causes the output stream that follows it to be printed with in a field of n characters wide, where n is the argument to setw(n). the output is right justified with in the field. If we do not use setw, the output is left justified by default and it occupies the space in the monitor equal to the number of characters in it. for example

cout<<“nepal”<<endl<<“beautiful”<<“country”;

OUTPUT
nepal
beautiful
country

Effect of using setw

cout<<setw(7)<<“nepal”<<endl<<setw(7)<<“beautiful”<<endl<<setw(7)<<“country”;

Output  
    nepal
beautiful
  country

This manipulators sets the n digit of precision to the right of the decimal point to the floating point, where n  is the argument to setprecision(n). for example

float a=20.456733, b=32.56789, c=64.45679, d=49.34689
cout<<a<<endl<<setprecision(3)<<b<<endl<<c<<endl<<setprecision(2)<<d;

Output
20.456733
32.567
64.456
49.34

Note: the header file for endl, setw and setprecision manipulators in c++ is iomanip.h. Manipulators are use to change the format of parameters on input/output streams and to insert certain special characters. And another type of manipulators are: with argument and non-argument.

Related term

Leave a Comment

Your email address will not be published. Required fields are marked *