Skip to main content

Features for formatting output

Short answer

Output formatting uses three mechanisms: (1) ios member functions (width, precision, fill, setf); (2) format flags (left/right, dec/hex, fixed/scientific, showpos); (3) manipulators (setw, setfill, setprecision, endl). Example: cout << setw(8) << setfill('*') << 42;

List the features that are used in formatting the output. Explain each with example.

C++ provides three groups of features to format output:

  1. ios class member functions
  2. ios format flags (with setf() / unsetf())
  3. Manipulators (<iomanip> and <iostream>)

1. ios member functions

  • width(n) – minimum field width, applies to the next item only.
  • precision(n) – number of significant digits (decimals with fixed).
  • fill(c) – padding character for unused field width.
  • setf(), unsetf() – set/clear flags.
cout.width(8); cout.fill('#'); cout << 42;      // ######42
cout.precision(3); cout << 3.14159;             // 3.14

2. Format flags

  • Justification: ios::left, ios::right, ios::internal
  • Base: ios::dec, ios::oct, ios::hex, with ios::showbase
  • Floating point: ios::fixed, ios::scientific, ios::showpoint
  • Others: ios::showpos, ios::uppercase, ios::boolalpha
cout.setf(ios::showpos);
cout.setf(ios::fixed, ios::floatfield);
cout.precision(2);
cout << 7.5;                                    // +7.50
cout.setf(ios::hex, ios::basefield);
cout << 255;                                    // ff

3. Manipulators

  • setw(n), setfill(c), setprecision(n), setiosflags(f), resetiosflags(f)
  • endl, ends, flush, dec, oct, hex, left, right, fixed, scientific
cout << setw(10) << setfill('*') << left << "Hi" << endl;   // Hi********
cout << hex << 255 << dec << " " << 255 << endl;             // ff 255

Complete example

#include <iostream>
#include <iomanip>
using namespace std;
int main() {
    cout << left  << setw(10) << "Item"
         << right << setw(8)  << "Price" << endl;
    cout << left  << setw(10) << "Book"
         << right << setw(8)  << fixed << setprecision(2) << 250.5 << endl;
    cout << left  << setw(10) << "Pen"
         << right << setw(8)  << 15.0 << endl;
    return 0;
}

Output:

Item         Price
Book        250.50
Pen          15.00

Difference in use

  • width() and setw() affect only the next value; the others stay until changed.
  • Manipulators can be chained inside one cout statement; ios functions need separate statements.

✓ Answer checked by Claude Opus 5.5 (high effort)

All Object Oriented Programming chapter 8 questions →