Loading lessons...
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:
setwonly affects the very next output, not all of them.
Precision and fixed notation
cout << fixed << setprecision(2) << 3.14159 << endl;
fixedswitches 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::coutis anostream- a stream of characters.setw(10)sizes the next field (right-justified by default).fixed+setprecision(2)prints 3.14159 as 3.14.std::flushpushes buffered output out without a newline.- Need
<iomanip>forsetwandsetprecision.