What are C++ Manipulators (endl, setw, setprecision, setf)?


Stream Manipulators are functions specifically designed to be used in conjunction with the insertion (<<) and extraction (>>) operators on stream objects, for example:

std::cout << std::setw(10);

They are still regular functions and can also be called as any other function using a stream object as an argument, for example:

boolalpha (cout);

Manipulators are used to changing formatting parameters on streams and to insert or extract certain special characters.

Following are some of the most widely used C++ manipulators:

endl

This manipulator has the same functionality as ‘\n’(newline character). But this also flushes the output stream.

Example

Live Demo

#include<iostream>
int main() {
   std::cout << "Hello" << std::endl << "World!";
}

Output

Hello
World!

showpoint/noshowpoint

This manipulator controls whether decimal point is always included in the floating-point representation. 

Example

 Live Demo 

#include <iostream>
int main() {
   std::cout << "1.0 with showpoint: " << std::showpoint << 1.0 << '\n'
             << "1.0 with noshowpoint: " << std::noshowpoint << 1.0 << '\n';
}

Output

1.0 with showpoint: 1.00000
1.0 with noshowpoint: 1

setprecision

This manipulator changes floating-point precision. When used in an expression out << setprecision(n) or in >> setprecision(n), sets the precision parameter of the stream out or into exactly n. 

Example

 Live Demo 

#include <iostream>
#include <iomanip>
int main() {
   const long double pi = 3.141592653589793239;
   std::cout << "default precision (6): " << pi << '\n'
             << "std::setprecision(10): " << std::setprecision(10) << pi << '\n';
}

Output

default precision (6): 3.14159
std::setprecision(10): 3.141592654

setw

This manipulator changes the width of the next input/output field. When used in an expression out << setw(n) or in >> setw(n), sets the width parameter of the stream out or in to exactly n. 

Example

Live Demo

#include <iostream>
#include <iomanip>
int main() {
   std::cout << "no setw:" << 42 << '\n'
             << "setw(6):" << std::setw(6) << 42 << '\n'
             << "setw(6), several elements: " << 89 << std::setw(6) << 12 << 34 << '\n';
}

Output

no setw:42
setw(6):    42
setw(6), several elements: 89    1234
raja
Published on 15-Feb-2018 16:55:18
Advertisements