What are stream manipulators?

0252

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:

  1. std::endl: Inserts a newline character and flushes the output buffer.

    std::cout << "Hello, World!" << std::endl;
  2. std::flush: Flushes the output buffer without inserting a newline.

    std::cout << "Flushing output" << std::flush;
  3. std::setw(int n): Sets the width of the next output field to n characters.

    std::cout << std::setw(10) << 42; // Outputs "        42"
  4. std::setprecision(int n): Sets the decimal precision for floating-point output.

    std::cout << std::setprecision(3) << 3.14159; // Outputs "3.14"
  5. std::fixed and std::scientific: Control the format of floating-point output. std::fixed displays numbers in fixed-point notation, while std::scientific displays them in scientific notation.

    std::cout << std::fixed << 3.14159; // Outputs "3.141590"
    std::cout << std::scientific << 3.14159; // Outputs "3.141590e+00"
  6. std::boolalpha and std::noboolalpha: Control the output format of boolean values. std::boolalpha outputs true and false, while std::noboolalpha outputs 1 and 0.

    std::cout << std::boolalpha << true; // Outputs "true"
  7. std::hex, std::dec, and std::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.

0 Comments

no data
Be the first to share your comment!