Stream manipulators in C++ are special functions or objects that are used to modify the behavior of input and output streams. They can be used to control formatting, such as how numbers are displayed, how text is aligned, and how data is read or written. Stream manipulators are typically used with the iostream library.
Common Stream Manipulators:
-
std::endl: Inserts a newline character and flushes the output buffer.std::cout << "Hello, World!" << std::endl; -
std::flush: Flushes the output buffer without inserting a newline.std::cout << "Flushing output" << std::flush; -
std::setw(int n): Sets the width of the next output field toncharacters.std::cout << std::setw(10) << 42; // Outputs " 42" -
std::setprecision(int n): Sets the decimal precision for floating-point output.std::cout << std::setprecision(3) << 3.14159; // Outputs "3.14" -
std::fixedandstd::scientific: Control the format of floating-point output.std::fixeddisplays numbers in fixed-point notation, whilestd::scientificdisplays them in scientific notation.std::cout << std::fixed << 3.14159; // Outputs "3.141590" std::cout << std::scientific << 3.14159; // Outputs "3.141590e+00" -
std::boolalphaandstd::noboolalpha: Control the output format of boolean values.std::boolalphaoutputstrueandfalse, whilestd::noboolalphaoutputs1and0.std::cout << std::boolalpha << true; // Outputs "true" -
std::hex,std::dec, andstd::oct: Change the base of integer output to hexadecimal, decimal, or octal, respectively.std::cout << std::hex << 255; // Outputs "ff" std::cout << std::dec << 255; // Outputs "255" std::cout << std::oct << 255; // Outputs "377"
Example:
Here’s a complete example demonstrating the use of some stream manipulators:
#include <iostream>
#include <iomanip> // For std::setw, std::setprecision, etc.
int main() {
std::cout << std::boolalpha; // Enable boolalpha
std::cout << "Boolean values:" << std::endl;
std::cout << "true: " << true << ", false: " << false << std::endl;
std::cout << std::endl;
std::cout << "Formatted output:" << std::endl;
std::cout << std::setw(10) << "Number" << std::setw(10) << "Square" << std::endl;
for (int i = 1; i <= 5; ++i) {
std::cout << std::setw(10) << i << std::setw(10) << (i * i) << std::endl;
}
std::cout << std::endl;
std::cout << std::setprecision(2) << std::fixed;
std::cout << "Pi: " << 3.14159 << std::endl;
return 0;
}
Summary:
Stream manipulators are powerful tools in C++ that enhance the formatting and presentation of output in streams, making it easier to create readable and well-structured output.
