Transcript Manipulator
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
(<<) and extractions (>>).
Examples:
endl, flush
oct, dec, hex (persistent effect: a change stays effective until
another change is requested)
int i = 10;
cout << i << ”
cout << oct <<
cout << hex <<
<< dec <<
” <<
i <<
i <<
i <<
i + i << endl;
” ” << i + i << endl;
” ” << i + i << ” ”
endl;
// 10 20
// 12 24
// a 14 10
decimal:
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
octal:
0 1 2 3 4 5 6 7 10 11 12 13 14 15 16 17 20 21 22 23 24
Hexdecimal: 0 1 2 3 4 5 6 7 8 9 a b c d e f 10 11 12 13 14
COMP102 Prog. Fundamentals I: Stream Manipulator Slide 3
Number Systems
Octal
Base 8
8 symbols
Hexadecimal
Base 16
16 symbols
More compact
representation of
the binary system
Decimal
00
01
02
...
07
08
09
10
11
...
15
16
...
749
Octal
00
01
02
...
07
10
11
12
13
...
17
20
...
1355
Hexadecimal
0
1
2
...
7
8
9
A
B
...
F
10
...
2ED
COMP102 Prog. Fundamentals I: Stream Manipulator Slide 4
More Stream Manipulators in
iomanip.h Library
#include <iomanip.h>
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
ios::scientific
Fixed-point notation (default: not set)
Example: 12.34
Floating-point notation (default: not set)
Example: 1.234e+001
ios::showpoint
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
ios::right
A plus (+) sign is shown before positive numbers
(default: not set)
Example: +12
Right-justified format when used with setw()
(default: set)
ios::left
Left-justified format when used with setw()
(default: not set)