3. • Display the contents of a format string
Format string can both contain:
1. Ordinary characters
Simply copy to the output line
2. Conversion specifications: %[format]
A place-holder representing a value to be filled in during printing.
%d: decimal digits of int value
%f: decimal digits of float value
Can display constants, variables, or more complicated expressions.
No limit on the number of values that can be printed by a single call of printf
Compiler are NOT required to check:
1. The number of conversion specifications in a format string matches the number of output items.
2. A conversion specification is appropriate for the type of item being printed.
3.1 The printf Function
printf(string, expr2, expr2, …);
int i;
float j;
printf(“%d %dn”, i);
printf(“%dn”, i, j);
printf(“%f %dn”, i, j);
4. 3.1 The printf Function: Conversion Specifications
Pros: Give the programmer a great deal of control over the appearance
of output.
Cons: Be complicated and hard to read.
%m.pX or %-m.pX
value Name Meaning Example (123.21) Output of Example
m Minimum field width
The minimum number of characters to print,
where minus (-) means left justification
%4d •123
%-4d 123•
p Precision Depends on the X
X Conversion specifier
Indicates which conversion should be
applied to the value before it’s printed.
%d 123
%f 123.21
5. 3.1 The printf Function: Conversion Specifications
%m.pX or %-m.pX
X Display Type p indicates?
d Integer in decimal form
Minimum number of digits to display
Default is 1
e
Floating-point number in
exponential format (scientific
notation)
How many digits should appear after the decimal point
Default is 6
f
Floating-point number in “fixed
decimal format”
How many digits should appear after the decimal point
Default is 6
g
Floating-point number in either
exponential format or fixed
decimal format, depending on
the number’s size
The maximum number of significant digits to be displayed
-> won’t show trailing zeros
Useful for displaying numbers tend to vary widely in size
Specifiers for
Integers
Ch7.1
Specifiers for
Floats
Ch7.2
Specifiers for
Characters
Ch7.3
Specifiers for
Strings
Ch13.3
Specifiers for
Others
Ch22.3
6. %i
• %i and %d
1. In printf format string, there is no difference between them
2. In scanf format string
%d can only match an integer written in decimal form
%i can match an integer expressed in octal, decimal, or hexadecimal
− If an input number has a 0 prefix, %i treats it as an octal number
− If it has a 0x or 0X prefix, %i treats it as a hex number
• Using %i instead of %d to read a number can have surprising results if the
user should accidentally put 0 at the beginning of the number
Octal
Numbers
Ch7.1
Hexadecimal
Numbers
Ch7.1
8. • Escape sequences enable strings
to contain characters that would
otherwise cause problems for
the compiler.
1. Nonprinting (control) characters
2. Special meanings characters
• A string may contain any
number of escape sequences.
3.1 The printf Function: Escape Sequences
Name Escape Sequence
Alert (bell) a
Backspace b
Form feed f
New line n
Carriage return r
Horizontal tab t
Vertical tab v
Backslash
Question mark ?
Single quote ’
Double quote ”
Escape
Sequences
Ch7.3
printf(“ItemtUnittPurchasentPricetDatan”);
Item Unit Purchase
Price Data
9. Escaping Sequences
1. %
• Using “%%” to print one “%” in format string
2. t
• How far apart tab stops are?
We cannot know in advance
The effect of printing t isn’t defined in C
Depend on OS
Tab stops are typically eight characters apart, but C makes no guarantee
10. 3.2 The scanf Function
• Read input according to a particular format
“Tightly packed” format strings like “%d%d%f%f” are common in scanf calls
Compiler are NOT required to check:
1. The number of conversion specifications in a format string matches the number of input
items.
2. A conversion specification is appropriate for the type of item being read.
3. Remember the & symbol may be needed to use.
-> Warning message: format argument is not a pointer
Many of our programs won’t behave properly if the user enters unexpected input.
It is possible to have a program test whether scanf successfully read the requested data and
attempt to recover if it didn’t
scanf(string, expr2, expr2, …);
11. 3.2 The scanf Function: How scanf Works
• Pattern-matching function that tries to match up groups of input
characters with conversion specifications
• Tries to locate an item of the appropriate type in the input data
• Skipping blank space if necessary
• Space, horizontal tab, vertical tab, form-feed, and new-line characters
• Numbers can be put on a single line or spread out over several lines
• Stopping when it encounters a character that can’t possibly belong to the
item
• scanf returns immediately without looking at the rest of the format string
once reading unsuccessfully
12. 3.2 The scanf Function: How scanf Works
• Integer
• First searches for a digit, a plus sign or
a minus sign
• Reads digits until it reaches a non-digit
• Floating-point
• A plus or minus sign (optional),
followed by
• A series of digits (possibly containing a
decimal point), followed by
• An exponent (optional).
• An exponent consists of the letter e (or E),
an optional sign, and one or more digits
• Rules of scanf follow to recognize an integer or a floating-point number:
scanf(“%d%d%f%f”, &i, &j, &x, &y);
1
-20 .3
-4.0e3
scanf peeks at the final new-line character without
actually reading it. This new-line will be the first
character read by the next call of scanf.
••1□-20•••.3□•••-4.0e3□
SS SR X
RRRSSSX
RR S SSSX
RRRRRR S
13. Scanf(1/2)
1. What does scanf do if it’s asked to read a number but the user enters
nonnumeric input?
• There are two conditions
1) The user enters a valid number, followed by nonnumeric characters
scanf reads and stores the number
The remaining characters are left to be read by the next call of scanf or some other input function
2) The input is invalid from the beginning
The value is undefined
The input this time left for the next scanf
• We can test whether a call of scanf has succeeded
• If the call fails, we can have the program either terminate or try to recover, perhaps
by discarding the offending input and asking the user to try again
Detecting
errors in scanf
Ch22.3
Q&A
Ch22
14. Scanf(2/2)
2. How scanf do put back characters and read them again later?
• Input is stored in a hidden buffer, to which scanf has access
• scanf can put characters back into the buffer for subsequent reading
3. What scanf do if the user puts punctuation marks (commas, for example)
between numbers?
• When scanf encounters a punctuation mark, scanf returns immediately since
numbers can’t begin with a punctuation mark
• The input after the punctuation mark and the number will be left for the next call of
scanf
Input/
Output
Ch22
15. 3.2 The scanf Function:
Ordinary Characters in Format Strings
1. White-space characters
A white-space character in a format string
matches any number of white-space
characters in the input, including none.
2. Other characters
scanf compares it with the next input
character
• Match
Discard the input character.
Continue processing the format string.
• Not Match
Put the offending character back into the input.
Abort without further processing the format string
or reading characters from the input.
Process an ordinary character in two way:
scanf(“%d/%d”, &i, &j);
•5/•96
•5•/•96 scanf(“%d /%d”, &i, &j);
When scanf attempts to
match ‘/’ after ‘5’, there is
no match.
The white-space before ‘96’ is
allowable because the white-
spaces before the conversion
specification is skipped.
16. 3.2 The scanf Function: Confusing printf with scanf
• Put & in front of variables in a call of printf
• Incorrect assuming that scanf format strings should resemble printf
format string
• Actually, there is often no need for a format string to include characters other than
conversion specifications since scanf normally skips white-space characters
• Put a new-line character at the end of a scanf format string is usually a
bad idea
• A format string like this can cause an interactive program to hang until the user
enters a nonblank character
scanf(“%d, %d”, &i, &j);
printf(“%d %dn”, &i, &j);