SlideShare a Scribd company logo
1 of 17
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

What's hot

What's hot (16)

Ch4 Expressions
Ch4 ExpressionsCh4 Expressions
Ch4 Expressions
 
STRINGS IN C MRS.SOWMYA JYOTHI.pdf
STRINGS IN C MRS.SOWMYA JYOTHI.pdfSTRINGS IN C MRS.SOWMYA JYOTHI.pdf
STRINGS IN C MRS.SOWMYA JYOTHI.pdf
 
C language basics
C language basicsC language basics
C language basics
 
Basic concept of c++
Basic concept of c++Basic concept of c++
Basic concept of c++
 
C language
C languageC language
C language
 
C programming part4
C programming part4C programming part4
C programming part4
 
C language UPTU Unit3 Slides
C language UPTU Unit3 SlidesC language UPTU Unit3 Slides
C language UPTU Unit3 Slides
 
Csharp4 operators and_casts
Csharp4 operators and_castsCsharp4 operators and_casts
Csharp4 operators and_casts
 
Overview of C Mrs Sowmya Jyothi
Overview of C Mrs Sowmya JyothiOverview of C Mrs Sowmya Jyothi
Overview of C Mrs Sowmya Jyothi
 
Ch03
Ch03Ch03
Ch03
 
Ch09
Ch09Ch09
Ch09
 
MANAGING INPUT AND OUTPUT OPERATIONS IN C MRS.SOWMYA JYOTHI.pdf
MANAGING INPUT AND OUTPUT OPERATIONS IN C    MRS.SOWMYA JYOTHI.pdfMANAGING INPUT AND OUTPUT OPERATIONS IN C    MRS.SOWMYA JYOTHI.pdf
MANAGING INPUT AND OUTPUT OPERATIONS IN C MRS.SOWMYA JYOTHI.pdf
 
C programing Tutorial
C programing TutorialC programing Tutorial
C programing Tutorial
 
Ch05
Ch05Ch05
Ch05
 
C programming session3
C programming  session3C programming  session3
C programming session3
 
Unit1 C
Unit1 CUnit1 C
Unit1 C
 

Similar to Ch3 Formatted Input/Output

T03 a basicioprintf
T03 a basicioprintfT03 a basicioprintf
T03 a basicioprintfteach4uin
 
T03 b basicioscanf
T03 b basicioscanfT03 b basicioscanf
T03 b basicioscanfteach4uin
 
Console I/o & basics of array and strings.pptx
Console I/o & basics of array and strings.pptxConsole I/o & basics of array and strings.pptx
Console I/o & basics of array and strings.pptxPRASENJITMORE2
 
Programming in c
Programming in cProgramming in c
Programming in cvineet4523
 
Chapter 2: Elementary Programming
Chapter 2: Elementary ProgrammingChapter 2: Elementary Programming
Chapter 2: Elementary ProgrammingEric Chou
 
2. introduction of a c program
2. introduction of a c program2. introduction of a c program
2. introduction of a c programAlamgir Hossain
 
Mesics lecture 5 input – output in ‘c’
Mesics lecture 5   input – output in ‘c’Mesics lecture 5   input – output in ‘c’
Mesics lecture 5 input – output in ‘c’eShikshak
 
Mesics lecture 5 input – output in ‘c’
Mesics lecture 5   input – output in ‘c’Mesics lecture 5   input – output in ‘c’
Mesics lecture 5 input – output in ‘c’eShikshak
 
20BCT23 – PYTHON PROGRAMMING.pptx
20BCT23 – PYTHON PROGRAMMING.pptx20BCT23 – PYTHON PROGRAMMING.pptx
20BCT23 – PYTHON PROGRAMMING.pptxgokilabrindha
 
Format string
Format stringFormat string
Format stringVu Review
 
Constant, variables, data types
Constant, variables, data typesConstant, variables, data types
Constant, variables, data typesPratik Devmurari
 

Similar to Ch3 Formatted Input/Output (20)

Lecture 3
Lecture 3Lecture 3
Lecture 3
 
Unit1 C
Unit1 CUnit1 C
Unit1 C
 
Chap 1 and 2
Chap 1 and 2Chap 1 and 2
Chap 1 and 2
 
Introduction
IntroductionIntroduction
Introduction
 
T03 a basicioprintf
T03 a basicioprintfT03 a basicioprintf
T03 a basicioprintf
 
Introduction to Input/Output Functions in C
Introduction to Input/Output Functions in CIntroduction to Input/Output Functions in C
Introduction to Input/Output Functions in C
 
Input And Output
 Input And Output Input And Output
Input And Output
 
C PADHLO FRANDS.pdf
C PADHLO FRANDS.pdfC PADHLO FRANDS.pdf
C PADHLO FRANDS.pdf
 
T03 b basicioscanf
T03 b basicioscanfT03 b basicioscanf
T03 b basicioscanf
 
Console I/o & basics of array and strings.pptx
Console I/o & basics of array and strings.pptxConsole I/o & basics of array and strings.pptx
Console I/o & basics of array and strings.pptx
 
Programming in c
Programming in cProgramming in c
Programming in c
 
C language
C languageC language
C language
 
Chapter 2: Elementary Programming
Chapter 2: Elementary ProgrammingChapter 2: Elementary Programming
Chapter 2: Elementary Programming
 
2. introduction of a c program
2. introduction of a c program2. introduction of a c program
2. introduction of a c program
 
Mesics lecture 5 input – output in ‘c’
Mesics lecture 5   input – output in ‘c’Mesics lecture 5   input – output in ‘c’
Mesics lecture 5 input – output in ‘c’
 
Mesics lecture 5 input – output in ‘c’
Mesics lecture 5   input – output in ‘c’Mesics lecture 5   input – output in ‘c’
Mesics lecture 5 input – output in ‘c’
 
20BCT23 – PYTHON PROGRAMMING.pptx
20BCT23 – PYTHON PROGRAMMING.pptx20BCT23 – PYTHON PROGRAMMING.pptx
20BCT23 – PYTHON PROGRAMMING.pptx
 
Format string
Format stringFormat string
Format string
 
Constant, variables, data types
Constant, variables, data typesConstant, variables, data types
Constant, variables, data types
 
Getting started with c++
Getting started with c++Getting started with c++
Getting started with c++
 

Recently uploaded

Current Transformer Drawing and GTP for MSETCL
Current Transformer Drawing and GTP for MSETCLCurrent Transformer Drawing and GTP for MSETCL
Current Transformer Drawing and GTP for MSETCLDeelipZope
 
Churning of Butter, Factors affecting .
Churning of Butter, Factors affecting  .Churning of Butter, Factors affecting  .
Churning of Butter, Factors affecting .Satyam Kumar
 
Artificial-Intelligence-in-Electronics (K).pptx
Artificial-Intelligence-in-Electronics (K).pptxArtificial-Intelligence-in-Electronics (K).pptx
Artificial-Intelligence-in-Electronics (K).pptxbritheesh05
 
OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...
OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...
OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...Soham Mondal
 
complete construction, environmental and economics information of biomass com...
complete construction, environmental and economics information of biomass com...complete construction, environmental and economics information of biomass com...
complete construction, environmental and economics information of biomass com...asadnawaz62
 
Introduction-To-Agricultural-Surveillance-Rover.pptx
Introduction-To-Agricultural-Surveillance-Rover.pptxIntroduction-To-Agricultural-Surveillance-Rover.pptx
Introduction-To-Agricultural-Surveillance-Rover.pptxk795866
 
Oxy acetylene welding presentation note.
Oxy acetylene welding presentation note.Oxy acetylene welding presentation note.
Oxy acetylene welding presentation note.eptoze12
 
Study on Air-Water & Water-Water Heat Exchange in a Finned Tube Exchanger
Study on Air-Water & Water-Water Heat Exchange in a Finned Tube ExchangerStudy on Air-Water & Water-Water Heat Exchange in a Finned Tube Exchanger
Study on Air-Water & Water-Water Heat Exchange in a Finned Tube ExchangerAnamika Sarkar
 
Gurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort service
Gurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort serviceGurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort service
Gurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort servicejennyeacort
 
Heart Disease Prediction using machine learning.pptx
Heart Disease Prediction using machine learning.pptxHeart Disease Prediction using machine learning.pptx
Heart Disease Prediction using machine learning.pptxPoojaBan
 
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdf
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdfCCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdf
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdfAsst.prof M.Gokilavani
 
main PPT.pptx of girls hostel security using rfid
main PPT.pptx of girls hostel security using rfidmain PPT.pptx of girls hostel security using rfid
main PPT.pptx of girls hostel security using rfidNikhilNagaraju
 
HARMONY IN THE HUMAN BEING - Unit-II UHV-2
HARMONY IN THE HUMAN BEING - Unit-II UHV-2HARMONY IN THE HUMAN BEING - Unit-II UHV-2
HARMONY IN THE HUMAN BEING - Unit-II UHV-2RajaP95
 
Software and Systems Engineering Standards: Verification and Validation of Sy...
Software and Systems Engineering Standards: Verification and Validation of Sy...Software and Systems Engineering Standards: Verification and Validation of Sy...
Software and Systems Engineering Standards: Verification and Validation of Sy...VICTOR MAESTRE RAMIREZ
 
Concrete Mix Design - IS 10262-2019 - .pptx
Concrete Mix Design - IS 10262-2019 - .pptxConcrete Mix Design - IS 10262-2019 - .pptx
Concrete Mix Design - IS 10262-2019 - .pptxKartikeyaDwivedi3
 
Sachpazis Costas: Geotechnical Engineering: A student's Perspective Introduction
Sachpazis Costas: Geotechnical Engineering: A student's Perspective IntroductionSachpazis Costas: Geotechnical Engineering: A student's Perspective Introduction
Sachpazis Costas: Geotechnical Engineering: A student's Perspective IntroductionDr.Costas Sachpazis
 

Recently uploaded (20)

Current Transformer Drawing and GTP for MSETCL
Current Transformer Drawing and GTP for MSETCLCurrent Transformer Drawing and GTP for MSETCL
Current Transformer Drawing and GTP for MSETCL
 
Churning of Butter, Factors affecting .
Churning of Butter, Factors affecting  .Churning of Butter, Factors affecting  .
Churning of Butter, Factors affecting .
 
Artificial-Intelligence-in-Electronics (K).pptx
Artificial-Intelligence-in-Electronics (K).pptxArtificial-Intelligence-in-Electronics (K).pptx
Artificial-Intelligence-in-Electronics (K).pptx
 
OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...
OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...
OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...
 
complete construction, environmental and economics information of biomass com...
complete construction, environmental and economics information of biomass com...complete construction, environmental and economics information of biomass com...
complete construction, environmental and economics information of biomass com...
 
Introduction-To-Agricultural-Surveillance-Rover.pptx
Introduction-To-Agricultural-Surveillance-Rover.pptxIntroduction-To-Agricultural-Surveillance-Rover.pptx
Introduction-To-Agricultural-Surveillance-Rover.pptx
 
Oxy acetylene welding presentation note.
Oxy acetylene welding presentation note.Oxy acetylene welding presentation note.
Oxy acetylene welding presentation note.
 
young call girls in Rajiv Chowk🔝 9953056974 🔝 Delhi escort Service
young call girls in Rajiv Chowk🔝 9953056974 🔝 Delhi escort Serviceyoung call girls in Rajiv Chowk🔝 9953056974 🔝 Delhi escort Service
young call girls in Rajiv Chowk🔝 9953056974 🔝 Delhi escort Service
 
Study on Air-Water & Water-Water Heat Exchange in a Finned Tube Exchanger
Study on Air-Water & Water-Water Heat Exchange in a Finned Tube ExchangerStudy on Air-Water & Water-Water Heat Exchange in a Finned Tube Exchanger
Study on Air-Water & Water-Water Heat Exchange in a Finned Tube Exchanger
 
Gurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort service
Gurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort serviceGurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort service
Gurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort service
 
Heart Disease Prediction using machine learning.pptx
Heart Disease Prediction using machine learning.pptxHeart Disease Prediction using machine learning.pptx
Heart Disease Prediction using machine learning.pptx
 
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdf
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdfCCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdf
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdf
 
main PPT.pptx of girls hostel security using rfid
main PPT.pptx of girls hostel security using rfidmain PPT.pptx of girls hostel security using rfid
main PPT.pptx of girls hostel security using rfid
 
HARMONY IN THE HUMAN BEING - Unit-II UHV-2
HARMONY IN THE HUMAN BEING - Unit-II UHV-2HARMONY IN THE HUMAN BEING - Unit-II UHV-2
HARMONY IN THE HUMAN BEING - Unit-II UHV-2
 
Software and Systems Engineering Standards: Verification and Validation of Sy...
Software and Systems Engineering Standards: Verification and Validation of Sy...Software and Systems Engineering Standards: Verification and Validation of Sy...
Software and Systems Engineering Standards: Verification and Validation of Sy...
 
Concrete Mix Design - IS 10262-2019 - .pptx
Concrete Mix Design - IS 10262-2019 - .pptxConcrete Mix Design - IS 10262-2019 - .pptx
Concrete Mix Design - IS 10262-2019 - .pptx
 
Sachpazis Costas: Geotechnical Engineering: A student's Perspective Introduction
Sachpazis Costas: Geotechnical Engineering: A student's Perspective IntroductionSachpazis Costas: Geotechnical Engineering: A student's Perspective Introduction
Sachpazis Costas: Geotechnical Engineering: A student's Perspective Introduction
 
🔝9953056974🔝!!-YOUNG call girls in Rajendra Nagar Escort rvice Shot 2000 nigh...
🔝9953056974🔝!!-YOUNG call girls in Rajendra Nagar Escort rvice Shot 2000 nigh...🔝9953056974🔝!!-YOUNG call girls in Rajendra Nagar Escort rvice Shot 2000 nigh...
🔝9953056974🔝!!-YOUNG call girls in Rajendra Nagar Escort rvice Shot 2000 nigh...
 
Design and analysis of solar grass cutter.pdf
Design and analysis of solar grass cutter.pdfDesign and analysis of solar grass cutter.pdf
Design and analysis of solar grass cutter.pdf
 
9953056974 Call Girls In South Ex, Escorts (Delhi) NCR.pdf
9953056974 Call Girls In South Ex, Escorts (Delhi) NCR.pdf9953056974 Call Girls In South Ex, Escorts (Delhi) NCR.pdf
9953056974 Call Girls In South Ex, Escorts (Delhi) NCR.pdf
 

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