C++ Crash Course: a fast-Paced Introduction



Yüklə 7 Mb.
Pdf görüntüsü
səhifə53/71
tarix20.09.2023
ölçüsü7 Mb.
#145939
1   ...   49   50   51   52   53   54   55   56   ...   71
C Crash Course A Fast-Paced Introduction by Josh Lospinoso

printf Format Specifiers
In addition to printing constant strings (like 
Hello, world!
in Listing 1-1), 
printf
can combine multiple values into a nicely formatted string; it is a spe-
cial kind of function that can take one or more arguments. 
The first argument to 
printf
is always a format string. The format string 
provides a template for the string to be printed, and it contains any num-
ber of special format specifiers. Format specifiers tell 
printf
how to interpret 
and format the arguments following the format string. All format specifiers 
begin with 
%
.
For example, the format specifier for an 
int
is 
%d
. Whenever 
printf
sees 

%d
in the format string, it knows to expect an 
int
argument following the 
format specifier. Then 
printf
replaces the format specifier with the argu-
ment’s actual value.
N O T E
 The 
printf
 function is a derivative of the 
writef
 function offered in BCPL, a defunct 
programming language designed by Martin Richards in 1967. Providing the specifiers 
%H

%I
, and 
%O
 to 
writef
 resulted in hexadecimal and octal output via the functions 
WRITEHEX

WRITED
, and 
WRITEOCT
. It’s unclear where the 
%d
 specifier comes from (perhaps 
the D in 
WRITED
?), but we’re stuck with it.


Up and Running
19
Consider the following 
printf
call, which prints the string 
Ten 10, Twenty 
20, Thirty 30
:
printf("Ten %d
u
, Twenty %d
v
, Thirty %d
w
", 10
x
, 20
y
, 30
z
);
The first argument, 
"Ten %d, Twenty %d, Thirty %d"
, is the format string. 
Notice that there are three format specifiers 
%d
u
v
w
. There are also three 
arguments after the format string 
x
y
z
. When 
printf
builds the output, it 
replaces the argument at 
u
with the one at 
x
, the argument at 
v
with the 
one at 
y
, and the argument at 
w
with the one at 
z
.

Yüklə 7 Mb.

Dostları ilə paylaş:
1   ...   49   50   51   52   53   54   55   56   ...   71




Verilənlər bazası müəlliflik hüququ ilə müdafiə olunur ©azkurs.org 2024
rəhbərliyinə müraciət

gir | qeydiyyatdan keç
    Ana səhifə


yükləyin