C++ Manipulators

C++ Manipulators: C++ Manipulators are nothing but functions that are designed to be used in the conjunction with the insertion(<<) and extraction(>>) operators on stream objects.

C++ Manipulators

Let us see some of the most commonly used manipulators in C++ language. They are as follows:

endl( ) Manipulator

This endl manipulator is known as the line feed operator in C++. The main purpose of this manipulator is to feed the whole line and then point the cursor to the beginning of the next line. If you want we can use the \n operators instead of using endl manipulator.

setw( ) Manipulator

This setw manipulator helps us to set the minimum field width on output.

Syntax: setw(x)

Example:

#include <iostream>
#include <iomanip>
using namespace std;
int main() {
float basic, ta,da,gs;
basic=10000; ta=800; da=5000;
gs=basic+ta+da;
cout<<setw(10)<<"Basic"<<setw(10)<<basic<<endl
<<setw(10)<<"TA"<<setw(10)<<ta<<endl
<<setw(10)<<"DA"<<setw(10)<<da<<endl
<<setw(10)<<"GS"<<setw(10)<<gs<<endl;
return 0;
}

Output:

Basic  10000
TA           800
DA        5000
GS      15800

Setfill( ) Manipulator

This setfill manipulator was used by the setw manipulator. It was used because if a value is not filled entirely in a field, then the character specified in the setfill argument is used for filling the fields.

Example:

#include <iostream>
#include <iomanip>
using namespace std;
int main() {
cout<< setw(10)<<setfill('*')<<"freshersnow.com"<<setw(10)<<setfill('*')<<"Test"<< endl;
}

Output:

*****freshersnow.com****************Test

Set Precision( ) Manipulator

The setprecision( ) manipulator is used to set the numbers to be displayed after the decimal point.

Syntax: setprecision( );

Example:

#include<iostream>//std::cout, std::fixed
#include<iomanip>//std::setprecision
int main() {
  double f =3.14159;
  std::cout<<std::setprecision(5)<<f<<'\n';
  std::cout<<std::setprecision(9)<<f<<'\n';
  std::cout<<std::fixed;
  std::cout<<std::setprecision(5)<<f<<'\n';
  std::cout<<std::setprecision(9)<<f<<'\n';
  return 0;
}

Output:

3.1416
3.14159
3.14159
3.141590000