Skip to main content

2. Write a cpp program which explains the use of a manipulators operator.

In C++, manipulators are special functions that can be used to modify the behavior of the stream insertion (<<) and stream extraction (>>) operators. They are often used to format output or parse input from streams, such as cout and cin.

Here's an example of how you can use manipulators to format output in C++:

#include <iostream>
#include <iomanip>

using namespace std;

void main()
{
cout << fixed << setprecision(2); // use fixed-point notation with 2 decimal places

cout << 123.4567 << endl; // prints 123.46
cout << 987.6543 << endl; // prints 987.65

cout << setw(10) << left; // set field width and left-justify values

cout << 123 << endl; // prints " 123"
cout << 456 << endl; // prints " 456"

return 0;
}

Output

123.46
987.65
123
456

In this example, we use the fixed and setprecision manipulators to specify that we want to use fixed-point notation with 2 decimal places when printing floating-point values. We also use the setw and left manipulators to set the field width and left-justify values when printing integers.

There are many other manipulators available in C++, including hex, oct, uppercase, boolalpha, and showpos.

You can find more information about manipulators in the C++ standard library documentation.