Skip to main content

3.4) Formatting Of Output


Examples

int x = 42;
cout << x << endl;                              // outputs "42"
cout << setw(5) << x << endl;                   // outputs "   42"
cout << setfill('*') << setw(5) << x << endl;   // outputs "***42"
cout << left << setw(5) << x << endl;           // outputs "42***"
cout << setw(7) << x << endl;                   // outputs "42*****"

Explanation

  • Formatting is done using stream manipulators, which are made available by adding #include <iomanip> to your program
  • Most manipulators make persistent changes to how an output stream does its formatting
  • The setw manipulator specifies field width (the minimum number of characters used for a value), for the next operation only
  • The setfill specifies the 'fill character' for an output field (space is the default)
  • The right manipulator positions the value to right of the output field and any fill characters to left (this is the default); the left manipulator does the opposite