lecture05-formatted IO

16 scanf scans each character in the input stream

Info iconThis preview shows page 1. Sign up to view the full content.

View Full Document Right Arrow Icon
This is the end of the preview. Sign up to access the rest of the document.

Unformatted text preview: ” scanf ( "Format string in quotes", &variable list)   scanf requires         a format string, followed by a list of variables into which input is to be stored Each variable must be preceded by &   Forge8ng to put the & symbol in front of a variable will have unpredictable —and possibly disastrous—results format strings are similar to prinA, but usually contain only conversion specifica=ons:           int i, j; float x, y; scanf("%d%d%f%f", &i, &j, &x, &y); For each conversion spec (L to R), find the next corresponding value in the input stream, and then assign it to the variable The type of variable, conversion spec and the input value should all match 15 Scanf (cont’d)   When used with scanf, e, f, and g conversions are iden=cal   each causes scanf to read a floa=ng ­point number   Use %le to read a double. 16 scanf ( ) scans each character in the input stream when searching for an input item to match a format code.     scanf ignores white ­space characters (blanks, tabs, and new ­line characters) while looking for data items If scanf is used in the following way: scanf("%d%d%f%f", &i, &j, &x, &y); Scanf does not ignore space when looking for characters in the format string…. We will discuss this in a minute the input could be split over several lines: 1  ­20 .3  ­4.0e3 or put on a single line: 1  ­20 .3  ­4.0e3 17 How scanf works (cont.)   When scanf encounters a character that can t be part of the current item, this character is scanned for the next input item or during the next call of scanf   Given: scanf("%d%d%f%f", &i, &j, &x, &y);   If the input is:   1 ­20.3 ­4.0e3   i = 1, j =  ­20, x = 0.3, y =  ­4.0e3   Arer reading an integer, scanf skips white ­space characters un=l it finds a non ­white ­space character   An interac=ve program will hang un=l the user enters a nonblank character. 18 The scanf Format String   A scanf format string may contain ordinary characters in addi=on to conversion specs   Non ­white ­space character must match the next input character or scanf terminates without reading further. (The non ­matching character can be read by a later call of scanf.)   For example, (int month, day, year;)  scanf("%d/%d/%d", &month, &day, &year);  7. will it read? Why or why not? **5...
View Full Document

This note was uploaded on 10/06/2013 for the course EE 312 taught by Professor Shafer during the Fall '08 term at University of Texas.

Ask a homework question - tutors are online