Download presentation
Presentation is loading. Please wait.
Published byLanny Hartono Modified over 6 years ago
1
Plan of the Day: More on type conversions scanf printf format strings
"C is quirky, flawed, and an enormous success." -- Dennis Ritchie Formatted I/O Topic 4 Dennis Ritchie Plan of the Day: More on type conversions scanf printf format strings Ritchie created the C programming language
2
Type Conversions
3
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 double num; int i; ... num = i; // i converted to double x = 3.14 * 2;// 2 converted to double
4
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 If f too large or small, may store garbage in i
5
Explicit Cast Syntax: (type-name) expression double num = 2.5;
double fracPart; fracPart = num – (int) num; // 0.5 int i = 7; int j = 2; double result = i/j; // result = ? double result2 = (float) i/j; // result2 = ? int result3 = i/j; // result3 = ?
6
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 2n where n = # of bits in representation Possibly prevent overflow with cast: long int goodNum; int okNum = 20000; goodNum = (long) j * j;
7
Formatted I/O
8
printf() function In <stdio.h>, standard IO library int x = ...;
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
9
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)
10
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.pX 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 g: floating point number in exponential or fixed format, depending on size. p = max number of significant digits. Won't display trailing zeros
11
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 0x or 0X. 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)
12
Example #include <stdio.h> int main(void){
/* example of formatted output */ int i = 40; double f = ; printf("|%d|%5d|%-5d|%5.3d|\n", i, i, i, i); printf("|%10.3f|%10.3e|%-10g|\n", f, f, f); } Output: |40| | | | | | e+02| |
13
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
14
Examples of printf Conversion Specifications
Examples showing the effect of flags on the %d conversion: Conversion Result of Applying Result of Applying Specification Conversion to 123 Conversion to –123 %8d •••••123 ••••-123 %-8d 123••••• -123•••• %+8d ••••+123 ••••-123 % 8d •••••123 ••••-123 %08d %-+8d +123•••• -123•••• %- 8d •123•••• -123•••• %+08d % 08d •
15
the scanf() function In standard I/O library <stdio.h> Example:
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
16
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 If a RETURN is entered after the number assigned to y, that RETURN is left for the next scanf to read. WHY? Because a \n was not in the format string and thus does not match the pattern scanf is expecting. Not the same for WHITE SPACE CHARS….. ANY number of WHITE SPACE chars in format string matches ANY number of WHITE SPACE chars in input, including NONE.
17
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
18
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: OR e3 -4.0e3 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
19
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 /%d", &month, &day, &year); will read: 5 / 28 / 2002 and similar inputs, regardless of whitespace before or after each / New-line character at end of scanf format string is usually a bad idea: scanf("%d\n", &i); Why? \n in format string makes scanf expect white-space – program may hang waiting for non-whitespace input
20
Formatted I/O Example /* Name: JoJo Programmer, EID = howdy312 Section: 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. */ #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 %.2d%.2d%.2d\n", year, month, day); } What would happened if the user did not input the two / symbols in the input? sample input and output Enter a date (mm/dd/yy): 2/17/96 You entered the date
21
Integer I/O: unsigned & hex
Reading/writing unsigned values: use %u unsigned int z; scanf(“%u”, &z) /* reads z in base 10 unsigned */ printf(“%u", z) /* writes z in base 10 unsigned */ Reading/writing in hex: use %x scanf(“%x", &z); /* reads z in base 16 */ printf(“%x", z); /* writes z in base 16 */ scanf(“%i”, &j); /*the value can be decimal, octal or hex */
22
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
23
Checking for Invalid Input
int 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
24
printf: fun stuff
25
Printing a Pointer Value
Use %p to print value of a pointer printf("%p",(void *) ptr); int x = 4; printf("x stored at %p\n", &x); prints memory address of x in hex
26
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%n\n", 123, &len);
Similar presentations
© 2024 SlidePlayer.com. Inc.
All rights reserved.