Chapter 3 Copyright ID: 351372
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.
Chapter 3: Formatted Input/Output Chapter 3 Copyright © 2008 W. W. Norton & Company. Chapter 3: Formatted Input/OutputThe 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/OutputOrdinary 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/OutputCompilers arent 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/OutputCompilers arent 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/OutputA 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/OutputThe , 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/OutputThe 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/OutputConversion 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, dependingonthenumberssize p indicatesthemaximum depending on numbers . p maximum number of significant digits to be displayed. The conversion wont show trailing zeros. If the number has no digits after the decimal point, doesnt display the decimal point.Copyright © 2008 W. W. Norton & Company.All rights reserved. Chapter 3: Formatted Input/OutputThe 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 st-7;.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/OutputThe 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/OutputA 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/OutputAnother 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/Outputscanfreads 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/OutputIn 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/OutputWhen 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 its the programmers responsibility to remember to Copyright © 2008 W. W. Norton & Company.All rights reserved. Chapter 3: Formatted Input/Outputscanftries 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/OutputAs 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 scanfpeeks at the final new-line without reading it.Copyright © 2008 W. W. Norton & Company.All rights reserved. Chapter 3: Formatted Input/OutputWhen 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 fora plus or minus sign (optional), followed bydigits (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/OutputWhen 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/OutputSample input: 1 - 203 - 40e3¤ 1 . 3 4 . The call of is the same as before:Heres 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 StringsWhen 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 dont 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 StringsExamples: Iftheformatstringis " andtheinputis If the input is fails, because the in the format string doesnt 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/OutputAlthough 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/OutputIncorrectly 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/OutputPutting 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 FractionsThe 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-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.