/
Chapter 3: Formatted Input/Output Chapter 3: Formatted Input/Output

Chapter 3: Formatted Input/Output - PDF document

lois-ondreau
lois-ondreau . @lois-ondreau
Follow
388 views
Uploaded On 2016-06-06

Chapter 3: Formatted Input/Output - PPT Presentation

Chapter 3 Copyright ID: 351372

Share:

Link:

Embed:

Download Presentation from below link

Download Pdf The PPT/PDF document "Chapter 3: Formatted Input/Output" is the property of its rightful owner. Permission is granted to download and print the materials on this web site for personal, non-commercial use only, and to display it on your personal computer provided you do not modify the materials and that you retain all copyright notices contained in the materials. By downloading content from our website, you accept the terms of this agreement.


Presentation Transcript

Chapter 3: Formatted Input/Output Chapter 3 Copyright © 2008 W. W. Norton & Company. Chapter 3: Formatted Input/Output•The function must be supplied with a f o a n y l t h a r e in r sting, oowedbyayvauestataetobeseted into the string during printing: •A conversion specification is a placeholder 2 Chapter 3: Formatted Input/Output•Ordinary characters in a format string are printed as they pp ear in the strin g ; conversion s p ecifications are re p laced. ppgpp •Example:int i, j;float x, y;i = 10;j = 20;x = 43.2892f; y=55270f; = 5527 . printf("i = %d, j = %d, x = %f, y = %f\n", i, j, x, y);•Output:i = 10, j = 20, x = 43.289200, y = 5527.000000Copyright © 2008 W. W. Norton & Company.All rights reserved. Chapter 3: Formatted Input/Output•Compilers aren’t requi numberofconversionspecificationsinaformat number a format string matches the number of output items.•Too many conversion specifications:•Too few conversion specifications: printf("%d \ n"ij);/***WRONG***/ printf("%d \ n" , , j); Copyright © 2008 W. W. Norton & Company.All rights reserved. 3 Chapter 3: Formatted Input/Output•Compilers aren’t requi conversionspecificationisappropriate conversion •If the programmer uses anthe program will produce meaningless output:printf("%f %d\n", i, x); /*** WRONG ***/ Copyright © 2008 W. W. Norton & Company.All rights reserved. Chapter 3: Formatted Input/Output•A conversion specification can have the form . p X , where m are inte g er constants and p , p g •Both •In the conversion specification 2, and •In the specification is 10 and the period) is missing, but in the specification is missing.Copyright © 2008 W. W. Norton & Company.All rights reserved. 4 Chapter 3: Formatted Input/Output•The , specifies the minimum number of characters to p rint. •If the value to be printed requires fewer than it is right-justified within the field.–%4ddisplays the number 123 as . (• represents the •If the value to be printed requires more than thefieldwidthautomaticallyexpandstothenecessarysize. field automatically •Putting a minus sign in front of causes left justification.–The specification would display 123 as Copyright © 2008 W. W. Norton & Company.All rights reserved. Chapter 3: Formatted Input/Output•The meaning of the , depends on the choiceof X the conversionspecifier choice X specifier •The specifier is used to display an integer in decimal form. indicates the minimum number of digits to display (extra zeros are added to the beginning of the number if –If is omitted, it is assumed to be 1.Copyright © 2008 W. W. Norton & Company.All rights reserved. 5 Chapter 3: Formatted Input/Output•Conversion specifiers for floating-point numbers: e — Exponentialformat p indicateshowmanydigits e . p how many should appear after the decimal point (the default is 6). If is 0, no decimal point is displayed.—“Fixed decimal” format. has the same meaning as for the —Either exponential format or fixed decimal format, dependingonthenumber’ssize p indicatesthemaximum depending on number’s . p maximum number of significant digits to be displayed. The conversion won’t show trailing zeros. If the number has no digits after the decimal point, doesn’t display the decimal point.Copyright © 2008 W. W. Norton & Company.All rights reserved. Chapter 3: Formatted Input/Output•The program uses displayintegersandfloating pointnumbersin numbers various formats. Copyright © 2008 W. W. Norton & Company.All rights reserved. 6 Chapter 3: Formatted Input/Output/* Prints int and float values in various formats */#include &#xst-7;&#x.500;dio.h ii(id) nt ma ( id) int i;float x;i = 40;x = 839.21f;printf("|%d|%5d|%-5d|%5.3d|\n", i, i, i, i);printf("|%10.3f|%10.3e|%-10g|\n", x, x, x); return 0;•Output:|40| 40|40 | 040|| 839.210| 8.392e+02|839.21 |Copyright © 2008 W. W. Norton & Company.All rights reserved. Chapter 3: Formatted Input/Output•The code that used in format strings is called an escapesequence an 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 Alert \ a Horizontal tabCopyright © 2008 W. W. Norton & Company.All rights reserved. 7 Chapter 3: Formatted Input/Output•A string may contain any number of escape sequences: sequences: •Executing this statement prints a two-line heading: Copyright © 2008 W. W. Norton & Company.All rights reserved. Chapter 3: Formatted Input/Output•Another common escape sequence is representsthe " •To print a single in the string: printf( " \ \ " \ \ /* prints one \character */Copyright © 2008 W. W. Norton & Company.All rights reserved. 8 Chapter 3: Formatted Input/Output•scanfreads input according to a particular format format •A format string may contain both ordinary •The conversions allowed with essentially the same as those used with Copyright © 2008 W. W. Norton & Company.All rights reserved. Chapter 3: Formatted Input/Output•In many cases, a format string will contain onlyconversionspecifications: only •Sample input: 1 203 40e3 1 - - Copyright © 2008 W. W. Norton & Company.All rights reserved. 9 Chapter 3: Formatted Input/Output•When using , the programmer must check thatthenumberofconversionspecifications that number matches the number of input variables and that each conversion is appropriate for the •Another trap involves the symbol, which normall p recedes each variable in a s canf •The is usually (but not always) required, and it’s the programmer’s responsibility to remember to Copyright © 2008 W. W. Norton & Company.All rights reserved. Chapter 3: Formatted Input/Output•scanftries to match groups of input characters withconversionspecificationsintheformatstring with format •For each conversion specification, locate an item of the appropriate type in the input •scanfthen reads the item, stopping when it reachesacharacterthatcan ’ tbelongtotheitem a cant –If the item was read successfully, processing the rest of the format string.–If not, returns immediately.Copyright © 2008 W. W. Norton & Company.All rights reserved. 10 Chapter 3: Formatted Input/Output•As it searches for a number, (space, horizontal and vertical tab, form-feed, and •A call of that reads four numbers:scanf("%d%d%f%f", &i, &j, &x, &y);•The numbers can be on one line or spread over several lines:-20 .3 40e3 0e3 •scanfsees a stream of characters (••1¤-20•••.3¤•••-4.0e3¤ssrsrrrsssrrssssrrrrrr •scanf“peeks” at the final new-line without reading it.Copyright © 2008 W. W. Norton & Company.All rights reserved. Chapter 3: Formatted Input/Output•When asked to read an integer, searchesforadigitaplussignoraminussign;it a a minus then reads digits until it reaches a nondigit.•When asked to read a floating-point number, looks for–a plus or minus sign (optional), followed by–digits (possibly containing a decimal point), followed by –an exponent (optional). An exponent consists of the letter ), an optional sign, and one or more digits.•%eare interchangeable when used Copyright © 2008 W. W. Norton & Company.All rights reserved. 11 Chapter 3: Formatted Input/Output•When partofthecurrentitemthecharacteris “ putback ” to be read again during the scanning of the next input item or during the next call of Copyright © 2008 W. W. Norton & Company.All rights reserved. Chapter 3: Formatted Input/Output•Sample input: 1 - 203 - 40e3¤ 1 . 3 4 . •The call of is the same as before:•Here’s how –%dcharacter back. %d Stores 20into j andputsthe characterback – . j . –%fcharacter back. –%f. Stores –4.0 ×103 into character back.Copyright © 2008 W. W. Norton & Company.All rights reserved. 12 Chapter 3: Formatted Input/OutputOrdinary Characters in Format Strings•When it encounters one or more white-space charactersinaformatstring, scanf readswhite - a format space characters from the input until it reaches a non-white-space character (which is “put back”).•When it encounters a non-white-space character in a format string, compares it with the next ut character. p –If they match, discards the input character and continues processing the format string.–If they don’t match, character back into the input, then aborts.Copyright © 2008 W. W. Norton & Company.All rights reserved. Chapter 3: Formatted Input/OutputOrdinary Characters in Format Strings•Examples: Iftheformatstringis " andtheinputis –If the input is fails, because the in the format string doesn’t match the space in the •To allow spaces after th fi / id f ormat str i ng %d" Copyright © 2008 W. W. Norton & Company.All rights reserved. 13 Chapter 3: Formatted Input/Output•Although calls of may appearsimilartherearesignificantdifferences similar are between the two.•One common mistake is to put variables in a call of printf("%d %d\n", &i, &j); /*** WRONG ***/ Copyright © 2008 W. W. Norton & Company.All rights reserved. Chapter 3: Formatted Input/Output•Incorrectly assuming that format strings shouldresemble printf formatstringsisanother should resemble format common error.•Consider the following call of –scanfwill first look for an integer in the input, which it stores in the variable i . –scanfwill then try to match a comma with the next input character.–If the next input character is a space, not a comma, will terminate without reading a value for Copyright © 2008 W. W. Norton & Company.All rights reserved. 14 Chapter 3: Formatted Input/Output•Putting a new-line charact scanf formatstringisusuallyabadidea. scanf format a •To , a new-line character in a format string is equivalent to a space; both cause advance to the next •If the format string is whitespacereadanintegerthenskiptothenext white •A format string like this program to “hang.”Copyright © 2008 W. W. Norton & Company.All rights reserved. Chapter 3: Formatted Input/OutputProgram: Adding Fractions•The program prompts the user to entertwofractionsandthendisplaystheirsum enter two •Sample program output: Enter second fraction: 3/4 Copyright © 2008 W. W. Norton & Company.All rights reserved. 15 Chapter 3: Formatted Input/Output/* Adds two fractions */#include stdio.h&#x-700; int main(void)int num1, denom1, num2, denom2, result_num, result_denom;printf("Enter first fraction: ");scanf("%d/%d", &num1, &denom1);printf("Enter second fraction: ");scanf("%d/%d", &num2, &denom2); result_num = num1 * denom2 + num2 *denom1;result_denom = denom1 * denom2;printf("The sum is %d/%d\n",result_num, result_denom)return 0;Copyright © 2008 W. W. Norton & Company.All rights reserved.