What is manipulator in C++?
In C++, a manipulator is a function that is used to modify the input or output formatting of a stream (such as std::cin
or std::cout
). Manipulators can be used to control how data is read from or written to the console, making them useful for formatting tasks like adjusting the width of an output, aligning text, or setting the precision for floating-point numbers.
Types of Manipulators in C++
1. Standard Manipulators
These are built-in manipulators that do not require arguments.
-
endl: Inserts a newline character and flushes the output buffer.
std::cout << "Hello" << std::endl; // Outputs "Hello" followed by a newline
-
setw: Sets the width of the next input/output operation.
std::cout << std::setw(10) << "Hi"; // Outputs "Hi" padded to 10 characters
-
setprecision: Sets the number of digits after the decimal point for floating-point numbers.
std::cout << std::setprecision(3) << 3.14159; // Outputs "3.14"
-
fixed and scientific: Used to display floating-point numbers in fixed-point or scientific notation.
std::cout << std::fixed << 123.456; // Outputs "123.456" std::cout << std::scientific << 123.456; // Outputs "1.234560e+02"
2. Custom Manipulators
You can also create custom manipulators to define specific behaviors or formats for input/output operations.
Example:
std::ostream& customEndl(std::ostream& out) { out << "\n--- End of Line ---\n"; return out; } std::cout << "Hello" << customEndl; // Outputs "Hello" followed by a custom message
Commonly Used Manipulators:
-
hex, oct, and dec: Used to change the number base (hexadecimal, octal, or decimal) for integer output.
std::cout << std::hex << 255; // Outputs "ff"
-
showpos: Displays the positive sign for numbers.
std::cout << std::showpos << 42; // Outputs "+42"
-
left, right, internal: Aligns output to the left, right, or internally within the specified width.
Sources:
GET YOUR FREE
Coding Questions Catalog