Programming Stream Manipulators
COMP102 Prog. Fundamentals I: Stream Manipulator Slide 2 Stream Manipulators in iostream.h Library I/O stream manipulators modify the behavior of insertions ( > ). l Examples: endl, flush oct, dec, hex (persistent effect: a change stays effective until another change is requested) int i = 10; cout << i << ” ” << i + i << endl; // cout << oct << i << ” ” << i + i << endl; // cout << hex << i << ” ” << i + i << ” ” << dec << i << endl; // a decimal: octal: Hexdecimal: a b c d e f
COMP102 Prog. Fundamentals I: Stream Manipulator Slide 3 Number Systems l Octal n Base 8 n 8 symbols l Hexadecimal n Base 16 n 16 symbols n More compact representation of the binary system Decimal Octal Hexadecimal A B F ED
COMP102 Prog. Fundamentals I: Stream Manipulator Slide 4 More Stream Manipulators in iomanip.h Library l #include Output manipulators (all except setw() are persistent): setprecision(d) - set number of significant digits to d ( d = 0 for default precision); enforce d decimal places by setting the I/O flag fixed setw(w) - set field width to w (or minimally larger than w to display the value correctly) setfill(c) - set fill character to c setiosflags(f) - set flag f to 1 resetiosflags(f) - set flag f to 0
COMP102 Prog. Fundamentals I: Stream Manipulator Slide 5 Formatting Flags (1/2) ios::fixed n Fixed-point notation (default: not set) Example: ios::scientific n Floating-point notation (default: not set) Example: 1.234e+001 ios::showpoint n Decimal point and trailing 0’s (default: not set) Example: 12.00
COMP102 Prog. Fundamentals I: Stream Manipulator Slide 6 Formatting Flags (2/2) ios::showpos A plus ( + ) sign is shown before positive numbers (default: not set) Example: +12 ios::right Right-justified format when used with setw() (default: set) ios::left Left-justified format when used with setw() (default: not set)