C++ Input / Output Manipulator

C++ Input / Output Manipulator

C++ provides a comprehensive library to manipulate input and output operations primarily through the stream classes. These classes use manipulators to format data in a specific manner.

Here's a brief tutorial on some of the most commonly used I/O manipulators:

  • Headers to Include: Before using I/O manipulators, ensure that you've included the necessary headers.

    #include <iostream> #include <iomanip> 
  • Setting Precision:

    double pi = 3.14159265; std::cout << std::setprecision(4) << pi; // 3.142 
  • Setting Field Width:

    std::cout << std::setw(10) << "Hello"; // Outputs " Hello" 
  • Setting Fill Character:

    std::cout << std::setw(10) << std::setfill('*') << "Hello"; // Outputs "*****Hello" 
  • Fixed and Scientific Notation:

    std::cout << std::fixed << pi; // 3.141593 std::cout << std::scientific << pi; // 3.141593e+00 
  • Manipulating Boolean Output:

    std::cout << std::boolalpha << true; // true std::cout << std::noboolalpha << true; // 1 
  • Manipulating Integer Output:

    int num = 255; std::cout << std::hex << num; // ff std::cout << std::oct << num; // 377 

    You can also display hexadecimal outputs in uppercase with std::uppercase:

    std::cout << std::hex << std::uppercase << num; // FF 
  • Setting internal, left, and right adjustments:

    std::cout << std::setw(10) << std::left << "Hello"; // "Hello " std::cout << std::setw(10) << std::right << "Hello"; // " Hello" std::cout << std::setw(10) << std::internal << "-42"; // "- 42" 
  • Showpos Manipulator: This manipulator ensures that the sign for positive numbers is also displayed.

    int posNum = 42; std::cout << std::showpos << posNum; // +42 
  • Setbase Manipulator: Allows you to set the base for integer numbers.

std::cout << std::setbase(16) << num; // ff 
  • Custom Manipulators: It's possible to create custom manipulators to perform specific tasks.
std::ostream& endline(std::ostream &output) { return output << "\n"; } std::cout << "Hello" << endline; 

This is just a basic overview. The C++ standard library offers many other manipulators and functionalities. The combination of these manipulators helps in precise formatting of data for user-friendly display or for data processing tasks. When working with I/O manipulators, always remember to include the necessary headers and be aware of the current state of the stream, as manipulators often modify this state.


More Tags

android-studio-2.2 docker-volume database-migration mms excel button fuzzywuzzy transparent rendering pass-by-reference

More Programming Guides

Other Guides

More Programming Examples