In: Computer Science
what are stream manipulators in C++? write a detail note.
Stream Manipulators are built in functions which are often used in conjunction with the insertion (<<) and extraction (>>) operators on stream objects.
The stream manipulators in C++ are given as:
This manipulator has the same functionality as ‘\n’(newline character). But this also flushes the output stream.
Example
#include<iostream> int main() { std::cout << "Hello" << std::endl << "World!"; }
Output
Hello World!
This manipulator changes floating-point precision.
Example
#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
This manipulator changes the width of the next input/output field.
Example
#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