Sams Teach Yourself C++ in 21 Days

(singke) #1
Working with Streams 617

17


LISTING17.13 Using fill()


0: // Listing 17.13 - fill()
1:
2: #include <iostream>
3: using namespace std;
4:
5: int main()
6: {
7: cout << “Start >”;
8: cout.width(25);
9: cout << 123 << “< End\n”;
10:
11: cout << “Start >”;
12: cout.width(25);
13: cout.fill(‘*’);
14: cout << 123 << “< End\n”;
15:
16: cout << “Start >”;
17: cout.width(25);
18: cout << 456 << “< End\n”;
19:
20: return 0;
21: }

Start > 123< End
Start >******************123< End
Start >******************456< End
Lines 7–9 repeat the functionality from the previous example by printing the
value 123 in a width area of 25. Lines 11–14 repeat this again, but this time, on
line 13, the fill character is set to an asterisk, as reflected in the output. You should notice
that unlike the width()function, which only applies to the next output, the new fill()
character remains until you change it. You see this verified with the output from lines
16–18.

Managing the State of Output: Set Flags
Objects are said to have state when some or all of their data represents a condition that
can change during the course of the program. For example, you can set whether to show
trailing zeros (so that 20.00 is not truncated to 20).
The iostreamobjects keep track of their state by using flags. You can set these flags by
calling setf()and passing in one of the predefined enumerated constants. For example,
to turn trailing zeros on, you call setf(ios::showpoint).
The enumerated constants are scoped to the iostreamclass (ios) and thus when used
with setf(), they are called with the full qualification ios::flagname, such as

OUTPUT


ANALYSIS
Free download pdf