C is quirky flawed and an enormous success

  • Slides: 26
Download presentation
"C is quirky, flawed, and an enormous success. " -- Dennis Ritchie Formatted I/O

"C is quirky, flawed, and an enormous success. " -- Dennis Ritchie Formatted I/O Topic 4 Plan of the Day: More on type conversions scanf printf format strings https: //en. wikiquote. org/wiki/Dennis_Ritchie Dennis Ritchie

Type Conversions

Type Conversions

Type Conversions • Implicit & explicit conversion • Implicit conversion occurs when: – operands

Type Conversions • Implicit & explicit conversion • Implicit conversion occurs when: – operands in expression are different types – type of function argument doesn't match parameter type – type of returned value doesn't match function's return type • Values converted to "larger" type x = 3. 14 * 2; // 2 converted to double num; int i; . . . num = i; // i converted to double

Type Conversion • Converting from "larger" to "smaller" type can be problematic int i;

Type Conversion • Converting from "larger" to "smaller" type can be problematic int i; float f; i = f; // value of f truncated • Use explicit cast if truncation intentional

Explicit Cast • Syntax: (type-name) expression double num = 2. 5; double frac. Part;

Explicit Cast • Syntax: (type-name) expression double num = 2. 5; double frac. Part; frac. Part = num – (int) num; // 0. 5 int i = 7; int j = 2; double result = i/j; // result = ? double result 2 = (float) i/j; // result 2 = ? int result 3 = i/j; // result 3 = ?

Overflow & Explicit Cast • Recall: Integer overflow – result of calculation is too

Overflow & Explicit Cast • Recall: Integer overflow – result of calculation is too large to be stored as an int • If operands signed: behavior is undefined • If operands unsigned: get the correct answer modulo 2 n where n = # of bits in representation • Possibly prevent overflow with cast: long int good. Num; int ok. Num = 20000; good. Num = (long) j * j;

Formatted I/O

Formatted I/O

printf() function • In <stdio. h>, standard IO library printf(“format-string” [, list-of-values]); • int

printf() function • In <stdio. h>, standard IO library printf(“format-string” [, list-of-values]); • int x =. . . ; printf (“the double of %d is %d n”, x, 2 * x ); Format string Conversion specifications Values to be printed Escape character for newline

printf() function • Format specifications based on type to be printed: – %d, %i:

printf() function • Format specifications based on type to be printed: – %d, %i: integer – %f: double in fixed-point format – %e: double value in exponential form – %g: double in normal or exponential form – %u: unsigned – %c: char – %s: C string (i. e. , null terminated char array) – %p: pointer (memory address)

printf() Format String • A printf conversion specification consists of the % character, followed

printf() Format String • A printf conversion specification consists of the % character, followed by as many as five distinct items: A conversion specification has the form %fm. p. X � f(optional) indicates left justification � default is right justification � there are other flags possible here as well m (optional) specifies the minimum field width. . p (optional) specifies: � Number of digits after the decimal point (for a floating point number) or � Minimum number of digits to print (for an integer) L (optional) is length modifier (e. g. , h, l) X is the basic data format used (e. g. d, e, f) For a more complete description of conversion specifications see Chapter 22. 3

printf Formatting • Flags (0 or more): Flag + Meaning Left-justify within field (default

printf Formatting • Flags (0 or more): Flag + Meaning Left-justify within field (default is right). Numbers produced by signed conversions always begin with + or -. space Nonnegative numbers produced by signed conversions are preceded by a space (+ flag overrides space). # Octal numbers begin with 0, nonzero hexadecimal numbers with 0 x or 0 X. Floating-point numbers always have a decimal point. Trailing zeros aren't removed from numbers printed with the g or G conversion codes. 0 Numbers are padded with leading zeros up to the field width (- flag overrides this)

Example #include <stdio. h> int main(void){ /* example of formatted output */ int i

Example #include <stdio. h> int main(void){ /* example of formatted output */ int i = 40; double f = 839. 21; printf("|%d|%5 d|%-5 d|%5. 3 d|n", i, i); printf("|%10. 3 f|%10. 3 e|%-10 g|n", f, f, f); } Output: |40| | 40|40 | 040| 839. 210| 8. 392 e+02|839. 21 |

printf Conversion Specifications • Length modifier (optional). Indicates that the item to be displayed

printf Conversion Specifications • Length modifier (optional). Indicates that the item to be displayed has a type that's longer or shorter than normal. – %d normally refers to an int value; %hd is used to display a short int and %ld is used to display a long int. – See table 22. 5 for more details

Examples of printf Conversion Specifications • Examples showing the effect of flags on the

Examples of printf Conversion Specifications • Examples showing the effect of flags on the %d conversion: Conversion Specification Result of Applying Conversion to 123 Result of Applying Conversion to – 123 %8 d %-8 d %+8 d %08 d %-+8 d %- 8 d %+08 d % 08 d • • • 123 • • • +123 • • • 123 00000123 +123 • • • 123 • • +0000123 • 0000123 • • -123 • • -123 -0000123 -123 • • • • -0000123

the scanf() function • In standard I/O library <stdio. h> scanf("format-string", variable-address-list); • In

the scanf() function • In standard I/O library <stdio. h> scanf("format-string", variable-address-list); • In list, specify address of variable where value will be stored • Use the address-of operator & before primitive type variables • Value is read from terminal, and stored in the memory location specified for next variable address in the list Example: int j; double x; printf("Please enter an integer and real number: "); scanf("%d%le", &j, &x); Store first value at address of j Store second value read at address of x

scanf() Function: Reading Numeric Values from Keyboard Syntax: scanf("Format-string", var-address-list); • Don't forget to

scanf() Function: Reading Numeric Values from Keyboard Syntax: scanf("Format-string", var-address-list); • Don't forget to put & before primitive type variables in list! • Format strings are similar to printf, but usually contain only conversion specifications: • int i, j; • float x, y; • scanf("%d%d%f%f", &i, &j, &x, &y); • For each specifier: find next corresponding value in the input stream, and assign it to the variable • Types of variable, conversion spec and the input value should match

scanf() • With scanf: e, f, and g conversions are identical – each causes

scanf() • With scanf: e, f, and g conversions are identical – each causes scanf to read a float – Use %le or %lf to read a double

How scanf works • scanf(): scans each character in the input stream while searching

How scanf works • scanf(): scans each character in the input stream while searching for an input item to match to a format code. – Ignores white-space characters (blanks, tabs, and new-line characters) until it finds non-white-space character • Reads item until a character that can't belong is found • Example: (Assume int i, j; float x, y; ): scanf ("%d%d%f%f", &i, &j, &x, &y); Input can be split over several lines or on single line: 1 OR 1 -20. 3 -4. 0 e 3 • The character found that is not part of the current item is put back and read again during the scanning of the next input item or the next call to scanf. – Watch out for the newline at the end of a scanf - stays in buffer

The scanf Format String • scanf format string: may contain ordinary characters in addition

The scanf Format String • scanf format string: may contain ordinary characters in addition to conversion specifications. • Non-white-space character: – matches next input character, OR – scanf terminates, leaving that character to be read later int month, day, year; scanf("%d/%d/%d", &month, &day, &year); • will successfully read 5/ 28/ 2002 but not 5 / 28 / 2002 • A white-space character in a format string matches zero or more white-space characters in the input. The call scanf("%d /%d", &month, &day, &year); will read: 5 / 28 / 2002 and similar inputs, regardless of whitespace before or after each /

Formatted I/O Example /* Name: Jo. Jo Programmer, EID = howdy 312 Section: 55555

Formatted I/O Example /* Name: Jo. Jo Programmer, EID = howdy 312 Section: 55555 Assignment: gazillionth Purpose: a program that prompts and accepts a date from the user in mm/dd/yy format and then displays it in yymmdd format. */ What would happened if the user did not input the two / symbols in the input? #include <stdio. h> int main( ) { int month, day, year; printf ("Enter a date (mm/dd/yy): "); /* user prompt */ scanf ("%d/%d/%d", &month, &day, &year); printf ("You entered the date %. 2 d%. 2 dn", year, month, day); } sample input and output Enter a date (mm/dd/yy): 2/17/96 You entered the date 960217

Integer I/O: unsigned & hex • Reading/writing unsigned values: use %u unsigned int z;

Integer I/O: unsigned & hex • Reading/writing unsigned values: use %u unsigned int z; scanf(“%u”, &z) printf(“%u", z) /* reads z in base 10 unsigned */ /* writes z in base 10 unsigned */ • Reading/writing in hex: use %x scanf(“%x", &z); printf(“%x", z); scanf(“%i”, &j); /* reads z in base 16 */ /* writes z in base 16 */ /*the value can be decimal, octal or hex */

Integer I/O: short & long • Reading/writing shorts: use %hd (or %ho, %hu, %hx)

Integer I/O: short & long • Reading/writing shorts: use %hd (or %ho, %hu, %hx) short int s; scanf(“%hd”, &s); • Reading/writing longs: use %ld (or %lo, %lu, %lx) long int t; printf(“%ld”, t); • Reading integer values in one of several bases int j; scanf("%i", &j); // value is decimal, octal or hex

Checking for Invalid Input input; scanf(“%d”, &input); • scanf returns: – # of items

Checking for Invalid Input input; scanf(“%d”, &input); • scanf returns: – # of items read, OR – EOF if failure occurs before any items read if(scanf(“%d”, &input) != 1)… • What if user enters non-integer value (e. g. , foo)? while(getchar() != ‘n’); // goodbye, bad user input and then re-prompt the user to input a different value

printf: fun stuff

printf: fun stuff

Printing a Pointer Value • Use %p to print value of a pointer printf("%p",

Printing a Pointer Value • Use %p to print value of a pointer printf("%p", (void *) ptr); int x = 4; printf("x stored at %pn", &x); • prints memory address of x in hex

printf: Number of Characters Printed • The %n conversion is used to find out

printf: Number of Characters Printed • The %n conversion is used to find out how many characters have been printed so far by a call of printf. • After the following call, the value of len will be 3: printf("%d%nn", 123, &len);