Lesson 19 +10 XP

Output with ostream and Manipulators

Output with ostream and Manipulators

std::cout is an object of type std::ostream - a stream for characters. You can tweak how it formats text using helpers called manipulators.

std::setw: column width

#include <iostream>
#include <iomanip>
using namespace std;

int main() {
    cout << setw(10) << 25 << endl;
    cout << setw(10) << 7 << endl;
    return 0;
}
  • setw(10) gives the next value a field ten characters wide.
  • By default the value is right-justified, so the numbers line up in a tidy column.
  • Important: setw only affects the very next output, not all of them.

Precision and fixed notation

cout << fixed << setprecision(2) << 3.14159 << endl;
  • fixed switches to decimal (fixed-point) notation.
  • setprecision(2) shows two digits after the dot.
  • Result: 3.14

std::flush: push it out now

The stream may hold output in a buffer before showing it. flush pushes it all out immediately:

cout << "Loading" << flush;

Note: endl flushes too, but flush does it without adding a newline.

Where do manipulators come from?

Some (like endl and flush) live in <iostream>. The fancier formatting ones (setw, setprecision, fixed) need <iomanip>.

TL;DR

  • std::cout is an ostream - a stream of characters.
  • setw(10) sizes the next field (right-justified by default).
  • fixed + setprecision(2) prints 3.14159 as 3.14.
  • std::flush pushes buffered output out without a newline.
  • Need <iomanip> for setw and setprecision.