Sams Teach Yourself C++ in 21 Days

(singke) #1
On line 16, the width is set to 10, and by default, the value is pushed to the extreme
right. On line 20, the width is again set to 10, but this time the alignment is set to the
left, and the number is printed flush left this time.
On line 25, again the width is set to 10, but this time the alignment is internal. Thus, the
0xis printed flush left, but the value,b9, is printed flush right.
Finally, on line 29, the concatenation operator setw()is used to set the width to 10, and
the value is printed again.
You should notice in this listing that if the flags are used within the coutlist that they do
not need to be qualified; hexcan be passed as hex. When you use the setf()function,
you need to qualify the flags to the class; hexis passed as ios::hex. You see this differ-
ence on line 17 versus 21.

Streams Versus the printf()Function................................................................


Most C++ implementations also provide the standard C I/O libraries, including the
printf()statement. Although printf()is in some ways easier to use than cout, it is
much less desirable.
printf()does not provide type safety, so it is easy to inadvertently tell it to display an
integer as if it were a character, and vice versa. printf()also does not support classes,
and so it is not possible to teach it how to print your class data; you must feed each class
member to printf()one by one.
Because there is a lot of legacy code using printf(), this section briefly reviews how
printf()is used. It is not, however, recommended that you use this function in your
C++ programs.
To use printf(), be certain to include the stdio.hheader file. In its simplest form,
printf()takes a formatting string as its first parameter and then a series of values as its
remaining parameters.
The formatting string is a quoted string of text and conversion specifiers. All conversion
specifiers must begin with the percent symbol (%). The common conversion specifiers are
presented in Table 17.2.

TABLE17.2 The Common Conversion Specifiers
Specifier Used For
%s strings
%d integers

620 Day 17

Free download pdf