Sams Teach Yourself C++ in 21 Days

(singke) #1
hello world
Hello again!
5
Here’s some values: 7 35 and also these: 98456 8.800000
Formatted: 7 35 8.800000
The first printf()statement, on line 5, uses the standard form: the term printf,
followed by a quoted string with a conversion specifier (in this case %s), followed
by a value to insert into the conversion specifier.
The %sindicates that this is a string, and the value for the string is, in this case, the
quoted string “hello world.”
The second printf()statement on line 8 is the same as the first, but this time a char
pointer is used, rather than quoting the string right in place in the printf()statement.
The result, however, is the same.
The third printf(), on line 11, uses the integer conversion specifier (%d), and for its
value the integer variable xis used. The fourth printf()statement, on line 19, is more
complex. Here, three values are concatenated. Each conversion specifier is supplied, and
then the values are provided, separated by commas. Line 20 is similar to line 19; how-
ever, different specifiers and values are used.
Finally, on line 23, format specifications are used to set the width and precision. As you
can see, all this is somewhat easier than using manipulators.
As stated previously, however, the limitation here is that no type checking occurs and
printf()cannot be declared a friend or member function of a class. So, if you want to
print the various member data of a class, you must call each accessor method in the argu-
ment list sent to the printf()statement.

OUTPUT


622 Day 17


ANALYSIS

FAQ
Can you summarize how to manipulate output?
Answer:(with special thanks to Robert Francis) To format output in C++, you use a com-
bination of special characters, output manipulators, and flags.
The following special characters are included in an output string being sent to coutusing
the insertion operator:
\n—Newline
\r—Carriage return
\t—Tab
\\—Backslash
\ddd(octal number)—ASCII character
\a—Alarm (ring bell)
Free download pdf