Programming in C

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

n Nothing gets read.The number of characters read so far by this call is written
into the intpointed to by the corresponding argument.
p The value to be read is a pointer expressed in the same format as is displayed
byprintfwith the %pconversion characters.The corresponding argument is
a pointer to a pointer to void.
% The next nonwhitespace character on input must be a %.

When scanfreads in a particular value, reading of the value terminates as soon as the
number of characters specified by the field width is reached (if supplied) or until a char-
acter that is not valid for the value being read is encountered. In the case of integers,
valid characters are an optionally signed sequence of digits that are valid for the base of
the integer that is being read (decimal: 0–9, octal: 0–7, hexadecimal: 0–9, a–f, or A–F).
For floats, permissible characters are an optionally signed sequence of decimal digits,
followed by an optional decimal point and another sequence of decimal digits, all of
which can be followed by the letter e(or E) and an optionally signed exponent. In the
case of %a,a hexadecimal floating value can be supplied in the format of a leading 0x,
followed by a sequence of hexadecimal digits with an optional decimal point, followed
by an optional exponent preceded by the letter p(or P).
For character strings read with the %sformat, any nonwhitespace character is valid. In
the case of %cformat, all characters are valid. Finally, in the case of the bracketed string
read, valid characters are only those enclosed within the brackets (or not enclosed within
the brackets if the ^character is used after the open bracket).
Recall from Chapter 9, “Working with Structures,” when you wrote the programs
that prompted the user to enter the time from the terminal, any nonformat characters
that were specified in the format string of the scanfcall were expected on the input.
So, for example, the scanfcall


scanf ("%i:%i:%i", &hour, &minutes, &seconds);


means that three integer values are to be read in and stored in the variables hour,
minutes,and seconds,respectively. Inside the format string, the :character specifies that
colons are expected as separators between the three integer values.
To specify that a percent sign is expected as input, double percent signs are included
in the format string, as follows:


scanf ("%i%%", &percentage);


Whitespace characters inside a format string match an arbitrary number of whitespace
characters on the input. So, the call


scanf ("%i%c", &i, &c);


with the line of text


29 w


Ta b le 16.6 Continued
Character Action
Free download pdf