Common stream manipulators in C++ are functions or objects that modify the behavior of input and output streams. Here are some of the most frequently used 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::fixed: Displays floating-point numbers in fixed-point notation.std::cout << std::fixed << 3.14159; // Outputs "3.141590" -
std::scientific: Displays floating-point numbers in scientific notation.std::cout << std::scientific << 3.14159; // Outputs "3.141590e+00" -
std::boolalpha: Outputs boolean values astrueorfalseinstead of1or0.std::cout << std::boolalpha << true; // Outputs "true" -
std::noboolalpha: Outputs boolean values as1or0instead oftrueorfalse.std::cout << std::noboolalpha << true; // Outputs "1" -
std::hex: Changes the base of integer output to hexadecimal.std::cout << std::hex << 255; // Outputs "ff" -
std::dec: Changes the base of integer output to decimal.std::cout << std::dec << 255; // Outputs "255" -
std::oct: Changes the base of integer output to octal.std::cout << std::oct << 255; // Outputs "377"
Summary:
These manipulators help control the formatting of output in C++, making it easier to present data in a readable and structured manner. They can be combined and used in various ways to achieve the desired output format.
