Programming in C

(Barry) #1
Formatted I/O: printfand scanf 355

The final set of output shows the use of the %nformat characters. In this case, the
corresponding argument to printfmust be of type pointer to int, unless a type modifi-
er of hh,h,l,ll,j,z, or tis specified.printfactually stores the number of characters it
has written so far into the integer pointed to by this argument. So, the first occurrence
of %ncauses printfto store the value 4 inside the integer variable c1because that’s how
many characters have been written so far by this call.The second occurrence of %ncaus-
es the value 12 to be stored inside c2. This is because 12 characters had been displayed at
that point by printf. Notice that inclusion of the %ninside the format string has no
effect on the actual output produced by printf.


The scanfFunction


Like the printffunction, many more formatting options can be specified inside the for-
mat string of a scanfcall than have been illustrated up to this point. As with printf,
scanftakes optional modifiers between the %and the conversion character.These
optional modifiers are summarized in Table 16.5.The possible conversion characters that
can be specified are summarized in Table 16.6.
When the scanffunction searches the input stream for a value to be read, it always
bypasses any leading so-called whitespacecharacters, where whitespacerefers to either a
blank space, horizontal tab ('\t'), vertical tab ('\v'), carriage return ('\r'), newline
('\n'), or form-feed character ('\f').The exceptions are in the case of the %cformat
characters—in which case, the next character from the input, no matter what it is, is
read—and in the case of the bracketed character string—in which case, the characters
contained in the brackets (or notcontained in the brackets) specify the permissible char-
acters of the string.


Ta b le 16.5 scanfConversion Modifiers


Modifier Meaning
* Field is to be skipped and not assigned
size Maximum size of the input field
hh Value is to be stored in a signedor unsigned char
h Value is to be stored in a short int
l Value is to be stored in a long int,double, or wchar_t
j,z, or t Value is to be stored in a size_t(%j),ptrdiff_t(%z),intmax_t,or
uintmax_t(%t)
ll Value is to be stored in a long long int
L Value is to be stored in a long double
type Conversion character
Free download pdf