VOOZH about

URL: https://www.geeksforgeeks.org/cpp/io-manipulation/

⇱ IO Manipulation in C++ - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

IO Manipulation in C++

Last Updated : 26 Mar, 2026

I/O manipulation in C++ refers to controlling the way input is read and the output is displayed using formatting tools and stream manipulators.

  • It helps customize how numbers, text, and values appear on the screen for better readability (alignment, precision, width, etc.).
  • It uses manipulators like setw, setprecision, fixed, and left/right for output control.

Output
 12.35

Explanation: This program formats the output by setting the width and precision, so the number is printed neatly with two decimal places and proper spacing.

Common I/O Formatting Techniques in C++:

1. Boolean Output Formatting

In C++, the bool data type is used to store Boolean values (true or false). By default, printing a Boolean value using cout outputs 1 for true and 0 for false. However, we can use manipulators to change this behavior.


Output
1
true
1

Explanation:

  • std::boolalpha: This manipulator causes the Boolean values to be printed as true or false instead of 1 or 0.
  • std::noboolalpha: Reverts the formatting back to printing 1 for true and 0 for false.

2. Changing Number Base (Decimal, Hexadecimal, Octal)

C++ allows us to display numbers in different numeral systems. By default, integers are displayed in decimal format, but we can use manipulators to change this to hexadecimal (std::hex) or octal (std::oct).


Output
26 20
1a 14
32 24
26 20

Explanation:

  • std::hex: Prints numbers in hexadecimal format (base 16).
  • std::oct: Prints numbers in octal format (base 8).
  • std::dec: Reverts back to the default decimal format (base 10).

3. Showing Base Prefix and Uppercase Hexadecimal

In certain cases, it is useful to display numbers with a prefix indicating their base (e.g., 0x for hexadecimal). Additionally, you may want to display hexadecimal letters in uppercase.


Output
032
0x1a
0x1a
0X1A

Explanation:

  • std::showpos adds a plus sign only for decimal output. It may not affect hexadecimal or octal representations.
  • std::uppercase: Converts letters in hexadecimal numbers to uppercase (e.g., a becomes A).

4. Width, Fill, and Alignment

C++ provides manipulators for controlling the width of the output and for filling empty spaces. You can set the fill character and control the alignment of the printed data.


Output
***12
***Hi
12***

Explanation:

  • std::setw(n): Sets the width of the output to n characters.
  • std::setfill(c): Specifies the character to be used for padding if the data is smaller than the set width. In this case, it is *.
  • std::left: aligns the output to the left within the given width. Other alignment options include std::right (default) and std::internal.
Comment
Article Tags:
Article Tags: