Chapter 3: Formatted Input/Output
Chapter 3: Formatted Input/Output
Chapter 3
Formatted Input/Output
1
4/3/2024
i = 10;
j = 20;
x = 43.2892f;
y = 5527.0f;
2
4/3/2024
Conversion Specifications
• A conversion specification can have the form %m.pX
or %-m.pX, where m and p are integer constants and
X is a letter.
• Both m and p are optional; if p is omitted, the period
that separates m and p is also dropped.
• In the conversion specification %10.2f, m is 10, p is
2, and X is f.
• In the specification %10f, m is 10 and p (along with
the period) is missing, but in the specification %.2f, p
is 2 and m is missing.
3
4/3/2024
Conversion Specifications
• The minimum field width, m, specifies the minimum
number of characters to print.
• If the value to be printed requires fewer than m characters,
it is right-justified within the field.
– %4d displays the number 123 as •123. (• represents the
space character.)
• If the value to be printed requires more than m characters,
the field width automatically expands to the necessary size.
• Putting a minus sign in front of m causes left justification.
– The specification %-4d would display 123 as 123•.
Conversion Specifications
• The meaning of the precision, p, depends on the
choice of X, the conversion specifier.
• The d specifier is used to display an integer in
decimal form.
– p indicates the minimum number of digits to display
(extra zeros are added to the beginning of the number if
necessary).
– If p is omitted, it is assumed to be 1.
4
4/3/2024
Escape Sequences
• The \n code that used in format strings is called
an escape sequence.
• Escape sequences enable strings to contain
nonprinting (control) characters and characters
that have a special meaning (such as ").
• A partial list of escape sequences:
Alert (bell) \a
Backspace \b
New line \n
Horizontal tab \t
5
4/3/2024
Escape Sequences
• A string may contain any number of escape
sequences:
printf("Item\tUnit\tPurchase\n\tPrice\tDate\n");
• Executing this statement prints a two-line heading:
Item Unit Purchase
Price Date
Escape Sequences
• Another common escape sequence is \", which
represents the " character:
printf("\"Hello!\"");
/* prints "Hello!" */
• To print a single \ character, put two \ characters
in the string:
printf("\\");
/* prints one \ character */
6
4/3/2024
7
4/3/2024