SlideShare a Scribd company logo
SC, Chen
Ch3 Formatted
Input / Output
Study Note of K. N. King(2008) ‘C Programming A Modern Approach, 2nd Edition’
Ch3 Formatted Input / Output
3.1 The printf Function
3.2 The scanf Function
• 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);
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
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
%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
3.1 The printf Function
• 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
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
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, …);
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
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
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
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
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.
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);
3.2 The scanf Function

More Related Content

PPTX
Ch7 Basic Types
PPTX
Ch8 Arrays
PPTX
Ch5 Selection Statements
PPTX
Ch6 Loops
PDF
Constants Variables Datatypes by Mrs. Sowmya Jyothi
PPT
C language Unit 2 Slides, UPTU C language
PDF
Unit ii chapter 2 Decision making and Branching in C
PPT
Basic of c &c++
Ch7 Basic Types
Ch8 Arrays
Ch5 Selection Statements
Ch6 Loops
Constants Variables Datatypes by Mrs. Sowmya Jyothi
C language Unit 2 Slides, UPTU C language
Unit ii chapter 2 Decision making and Branching in C
Basic of c &c++

What's hot (16)

PPTX
Ch4 Expressions
PDF
STRINGS IN C MRS.SOWMYA JYOTHI.pdf
PPT
C language basics
PPT
Basic concept of c++
PDF
C language
PDF
C programming part4
PPT
C language UPTU Unit3 Slides
PPT
Csharp4 operators and_casts
PPTX
Overview of C Mrs Sowmya Jyothi
PDF
MANAGING INPUT AND OUTPUT OPERATIONS IN C MRS.SOWMYA JYOTHI.pdf
PDF
C programing Tutorial
PDF
C programming session3
PPT
Unit1 C
Ch4 Expressions
STRINGS IN C MRS.SOWMYA JYOTHI.pdf
C language basics
Basic concept of c++
C language
C programming part4
C language UPTU Unit3 Slides
Csharp4 operators and_casts
Overview of C Mrs Sowmya Jyothi
MANAGING INPUT AND OUTPUT OPERATIONS IN C MRS.SOWMYA JYOTHI.pdf
C programing Tutorial
C programming session3
Unit1 C
Ad

Similar to Ch3 Formatted Input/Output (20)

PPTX
Lecture 3
PPT
Unit1 C
PPTX
basics of c programming for naiver.pptx
PPT
PDF
Introduction
PPT
T03 a basicioprintf
PDF
Introduction to Input/Output Functions in C
PPT
Input And Output
PDF
C PADHLO FRANDS.pdf
PPT
T03 b basicioscanf
PPTX
Console I/o & basics of array and strings.pptx
PPTX
4 Introduction to C.pptxSSSSSSSSSSSSSSSS
PPSX
Programming in c
PPTX
C language
PPTX
Chapter 2: Elementary Programming
PPTX
PPS_unit_2_gtu_sem_2_year_2023_GTUU.pptx
PPTX
basic C PROGRAMMING for first years .pptx
PPTX
2. introduction of a c program
PPT
Mesics lecture 5 input – output in ‘c’
PPT
Mesics lecture 5 input – output in ‘c’
Lecture 3
Unit1 C
basics of c programming for naiver.pptx
Introduction
T03 a basicioprintf
Introduction to Input/Output Functions in C
Input And Output
C PADHLO FRANDS.pdf
T03 b basicioscanf
Console I/o & basics of array and strings.pptx
4 Introduction to C.pptxSSSSSSSSSSSSSSSS
Programming in c
C language
Chapter 2: Elementary Programming
PPS_unit_2_gtu_sem_2_year_2023_GTUU.pptx
basic C PROGRAMMING for first years .pptx
2. introduction of a c program
Mesics lecture 5 input – output in ‘c’
Mesics lecture 5 input – output in ‘c’
Ad

Recently uploaded (20)

PPTX
KTU 2019 -S7-MCN 401 MODULE 2-VINAY.pptx
PPTX
bas. eng. economics group 4 presentation 1.pptx
PPTX
Foundation to blockchain - A guide to Blockchain Tech
PPTX
Engineering Ethics, Safety and Environment [Autosaved] (1).pptx
PPTX
FINAL REVIEW FOR COPD DIANOSIS FOR PULMONARY DISEASE.pptx
PDF
Automation-in-Manufacturing-Chapter-Introduction.pdf
PDF
TFEC-4-2020-Design-Guide-for-Timber-Roof-Trusses.pdf
PDF
July 2025 - Top 10 Read Articles in International Journal of Software Enginee...
DOCX
573137875-Attendance-Management-System-original
PDF
Mohammad Mahdi Farshadian CV - Prospective PhD Student 2026
PPTX
UNIT 4 Total Quality Management .pptx
PDF
PPT on Performance Review to get promotions
PPTX
CYBER-CRIMES AND SECURITY A guide to understanding
PPTX
M Tech Sem 1 Civil Engineering Environmental Sciences.pptx
PDF
Model Code of Practice - Construction Work - 21102022 .pdf
PPTX
CH1 Production IntroductoryConcepts.pptx
PPTX
Geodesy 1.pptx...............................................
PDF
Enhancing Cyber Defense Against Zero-Day Attacks using Ensemble Neural Networks
PDF
R24 SURVEYING LAB MANUAL for civil enggi
PPTX
MET 305 2019 SCHEME MODULE 2 COMPLETE.pptx
KTU 2019 -S7-MCN 401 MODULE 2-VINAY.pptx
bas. eng. economics group 4 presentation 1.pptx
Foundation to blockchain - A guide to Blockchain Tech
Engineering Ethics, Safety and Environment [Autosaved] (1).pptx
FINAL REVIEW FOR COPD DIANOSIS FOR PULMONARY DISEASE.pptx
Automation-in-Manufacturing-Chapter-Introduction.pdf
TFEC-4-2020-Design-Guide-for-Timber-Roof-Trusses.pdf
July 2025 - Top 10 Read Articles in International Journal of Software Enginee...
573137875-Attendance-Management-System-original
Mohammad Mahdi Farshadian CV - Prospective PhD Student 2026
UNIT 4 Total Quality Management .pptx
PPT on Performance Review to get promotions
CYBER-CRIMES AND SECURITY A guide to understanding
M Tech Sem 1 Civil Engineering Environmental Sciences.pptx
Model Code of Practice - Construction Work - 21102022 .pdf
CH1 Production IntroductoryConcepts.pptx
Geodesy 1.pptx...............................................
Enhancing Cyber Defense Against Zero-Day Attacks using Ensemble Neural Networks
R24 SURVEYING LAB MANUAL for civil enggi
MET 305 2019 SCHEME MODULE 2 COMPLETE.pptx

Ch3 Formatted Input/Output

  • 1. SC, Chen Ch3 Formatted Input / Output Study Note of K. N. King(2008) ‘C Programming A Modern Approach, 2nd Edition’
  • 2. Ch3 Formatted Input / Output 3.1 The printf Function 3.2 The scanf Function
  • 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
  • 7. 3.1 The printf Function
  • 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);
  • 17. 3.2 The scanf Function