Input & Output Operations SCP1103 Basic C Programming SEM1 2010/2011 Week 6 Input & Output Operations
Formatted input / output In C, data must be input to and output from a program through a file
Formatted input / output Other then printf and scanf, C provides other function for input and output operation using library <stdio.h> & <conio.h> Example: conio.h : clrscr getch inport stdio.h : scanf getchar feof
6.1 Formatting Output
Formatting Output with printf Precise output formatting Conversion specifications: flags, field widths, precisions, etc. Can perform rounding, aligning columns, right/left justification, inserting literal characters, exponential format, hexadecimal format, fixed width and precision
Formatting Output with printf Format of printf statement printf( format-control-string, other-arguments ); Format control string: describes output format Ordinary characters - copy to output stream: Example – printf(“this is an output\n”);
Formatting Output with printf Format of printf statement printf( format-control-string, other-arguments ); Other-arguments: correspond to each conversion specification in format-control-string Each specification begins with a percent sign (%), ends with conversion specifier
Formatting Output with printf Format of printf statement
Formatting Output with printf Format of printf statement printf( format-control-string, other-arguments ); Other-arguments: Conversion specifications: leading with character ‘%’ Format: %-w.p[d,f,c,s,…] [-]: optional left justification, if exists [w]: optional minimal width (wider if necessary). [.]: optional separates field w and p [p]: optional maximum field width for a string precision of floating number [d,f,c,s,…] : match to variable data type 9
Printing variable values To print an integer: int degreesF = 68; printf("The temperature is %d degrees.", degreesF); Specifier for “print an integer value” “Read value from this variable” Output: > The temperature is 68 degrees.
printf() Format specifiers: %c for single characters %d for integers %f for float/double (fractions): 1234.56 %g for float/double (scientific): 1.23456E+3 %s for phrases or ‘strings’ (coming soon!)
Integer Conversion Specifier
Printing Character A 65 41 101 char a; printf("%c %d %x %0", a, a, a, a); A 65 41 101
Printing Integers Integer Whole number (no decimal point): 25, 0, -9 Positive, negative, or zero Only minus sign prints by default
Example 1 Output: 455 -455 32000 2000000000 707 4294966841 1c7 1C7
Printing Floating-Point Numbers Have a decimal point (33.5) Exponential notation (computer's version of scientific notation) 150.3 is 1.503 x 10² in scientific 150.3 is 1.503E+02 in exponential (E stands for exponent) use e or E f – print floating point with at least one digit to left of decimal g (or G) - prints in f or e with no trailing zeros (1.2300 becomes 1.23)
Floating-point conversion specifiers
Example Program Output 1.234568e+006 -1.234568e+006 1.234568E+006 1234567.890000 1.23457e+006 1.23457E+006
Printing Strings and Characters Prints char argument Cannot be used to print the first character of a string s Requires a pointer to char as an argument Prints characters until NULL ('\0') encountered Cannot print a char argument Remember Single quotes for character constants ('z') Double quotes for strings "z" (which actually contains two characters, 'z' and '\0')
Other Conversion Specifiers Displays pointer value (address) n Stores number of characters already output by current printf statement Takes a pointer to an integer as an argument Nothing printed by a %n specification Every printf call returns a value Number of characters output Negative number if error occurs % Prints a percent sign %%
Printing with Field Widths and Precisions Size of field in which data is printed If width larger than data, default right justified If field width too small, increases to fit data Minus sign uses one character position in field Integer width inserted between % and conversion specifier %4d – field width of 4
Printing with Field Widths and Precisions Meaning varies depending on data type Integers (default 1) Minimum number of digits to print If data too small, prefixed with zeros Floating point Number of digits to appear after decimal (e and f) For g – maximum number of significant digits Strings Maximum number of characters to be written from string Format Use a dot (.) then precision number after % %.3f
Printing with Field Widths and Precisions Field width and precision Can both be specified %width.precision %5.3f Negative field width – left justified Positive field width – right justified Precision must be positive
Example printf("|%d|\n", 987); printf("|%2d|\n", 987); printf("|%8d|\n", 987); printf("|%-8d|\n", 987); printf("|%0.2f|\n", 9876.54); printf("|%4.2f|\n", 9876.54); printf("|%3.1f|\n", 9876.54); printf("|%10.3f|\n", 9876.54); printf("|%10.3e|\n", 9876.54); |987| | 987| |987 | |9876.54| |9876.5| | 9876.540| | 9.876e+03|
Example ▪ ▪ ▪1 ▪ ▪12 ▪123 1234 12345 ▪ ▪-1 ▪-12 -123 -1234 -12345
Example Using precision for integers 0873 000000873 Using precision for floating-point numbers 123.945 1.239e+002
Printing Literals and Escape Sequences Most characters can be printed Certain "problem" characters, such as the quotation mark " Must be represented by escape sequences Represented by a backslash \ followed by an escape character
Printing Escape Sequences
Identify the output of the following statements: Exercise Week 6_1 Identify the output of the following statements: printf(“Ant’s Length:%2.2f sm",2.445e-2); printf("%c %d %u", 66, 0x50, 'C'); printf("%-8d\n%6.3f %-6.3f", 4356, 1.52, 1.52);
6.2 Formatted Input
Formatting Input with scanf Input formatting (i.e. will scan formatted input from the keyboard – data entry purpose) Capabilities Input all types of data Input specific characters Skip specific characters
Formatting Input with scanf scanf(format-control-string, other-arguments); Format-control-string Describes formats of inputs Other-arguments Pointers to variables where input will be stored
Keyboard input: scanf() Example - to read an integer: int num_students; scanf(" %d", &num_students); Specifier for “read an integer value” VERY IMPORTANT special symbol (&) ‘address of’ operator “Place value into this variable”
Formatting Input with scanf
Formatting Input with scanf
Formatting Input with scanf
Formatting Input with scanf
Example
Example
Example Program Output Enter a string: Sunday The input was: the character "S" and the string "unday"
Exercise Week 6_2 Refer to Exercise 2 No. 1 in pg. 56. What will be displayed if the following characters are entered in Program 6.1 & 6.2. Explain the program output with the following input. AV TY
6.3 Simple Input Output
getchar() & putchar() Use library stdio.h getchar() - to read a single character from standard input - keyboard. Pressing Enter causes the block of characters you typed to be made available to your program. putchar() - to write a single character to standard output – output monitor. Example: char huruf; huruf = getchar(); putchar (huruf); putchar (huruf+1); Output with input ‘E’: EF
getch() & putch() Use library conio.h getch() - to read a single character from standard input - keyboard. The block of characters you typed available directly to your program. No need to press enter. Does not echo the input. putch() - to write a single character to standard output - monitor. Example: char huruf; huruf = getch(); putch (huruf+1); Output with input ‘E’: F
getc() & putc() Use library conio.h getc() - to read a single character from standard input device – e.g. keyboard & file. With stdin device type work similar with getchar(). putc() - to write a single character to standard output device – e.g. monitor & file. Example: char huruf; huruf = getc(stdin); putc (huruf, stdout);
gets() & puts() Use library stdio.h gets() - to read strings standard input device Pressing Enter causes the strings you typed to be made available to your program. The new line character will be stored as null (‘\0’) puts() - to write string to standard output device. To change null (‘\0’) to new line. Example – input string “Dayang Norhayati” & store as: D a y n g N o r h t i \0
gets() & puts() Good day Dayang Norhayati It's your lucky day !! #include <stdio.h> #include <conio.h> void main () { char nama[30]; printf("\nEnter Your Name please >>"); gets(nama); /*read string*/ printf("Good day "); puts(nama); /*print string*/ puts("It's your lucky day !!"); getch(); return 0; } Good day Dayang Norhayati It's your lucky day !!
Exercise Week 6_3 Write C program to solve the flow chart.
6.4 Hand Tracing a Program
Useful to locate logic or mathematical errors Hand Tracing a Program Hand trace a program: act as if you are the computer, executing a program: step through and ‘execute’ each statement, one-by-one record the contents of variables after statement execution, using a hand trace chart (table) Useful to locate logic or mathematical errors
Hand Tracing a Program The average is 1.1 int main () { float num1, num2,num3, avg; printf("Enter the first number> "); scanf("%f", &num1); printf("Enter the second number> "); scanf("%f", &num2); printf("Enter the third number> "); scanf("%f", &num3); avg=(num1+num2+num3)/3; printf("The average is %f", avg); getch(); return 0; } num1 num2 num3 avg ? 1.1 2.2 3.3 The average is 1.1
Trace the following programs Exercise Week 6_4 Trace the following programs void main(){ //Prog 6_41 int x, y, z; x =10; y = 17; z = x + y; y = y - x; printf ("x: %d y: %d z: %d”, x, y, z); x = y * z; z = x / 20; y = z % x; cout<<"\nx: "<<x<< " y: “ <<y<<" z: "<<z; getch(); } void main(){//Prog 6_42 int n, m, x, y; m=10; n=m*2/(m+2); m%=n+2; cout <<"n: "<<n; cout <<"\nm: "<<m; x=4; y=x*2+10%3-1*x; x*=(y/m); cout<<"\nx: "<< x; cout<<"\ny: "<<y; getch(); }
Introduction to File Input and Output 6.5 Introduction to File Input and Output
Introduction to File Input and Output Can use files instead of keyboard, monitor screen for program input, output Allows data to be retained between program runs We use a file for three purposes: reading data from it writing or printing data into it reading and writing data from/into it These are called file modes
Introduction to File Input and Output A file that is used for reading is called an input file (or data file) A file that is used for writing is called an output file We cannot read data from an output file & we cannot write data into an input file
Files: What is Needed Steps: Create the file Open the file Use the file (read from, write to, or both) Close the file
e.g. declaration of file variable Creating File To cerate internal name Creating an internal name means declaring a variable for the file - using pointer data type, FILE e.g. declaration of file variable
file_variable = fopen(“filename”, “file_mode”); Opening Files Create a link between file name (outside the program) and file stream object (inside the program) Use the fopen member function: file_variable = fopen(“filename”, “file_mode”); Filename may include drive, path info. File mode tells the program how you intend to use the file –for reading or writing or both.
Opening Files – File Mode Meaning r Open file for reading => an input file • If file exists, the file marker is positioned at beginning. & If file doesn’t exist errors returned. w Open file for writing => an output file • If file exists, it is emptied. & If file doesn’t, it is created. a Open file for appending = > an output file • If file exists, the file marker is positioned at end of file. & If file doesn’t exist, it is created. r+ Open an existing file for both reading & writing w+ Open a new file for both reading & writing a+ Open an existing file for both reading & writing & append at the end of the file
Using Files Can use output file using fprintf: fprintf(file_variable,”format string”,value_list); Can use input file using fscanf: fscanf(file_variable,”format string”,address_list); fgetc & fputc: to read or print a character from file or to file. fgets & fputs: to read or print strings from file or to file.
Use the close member function: Closing Files Use the close member function: fopen(file_variable); Don’t wait for operating system to close files at program end: may be limit on number of open files may be buffered output data waiting to send to file
Files - example Create 2 files Open file to read Open file to write #include <stdio.h> #define PI 3.14159 int main(void) { double radius,area, circumference ; FILE *inp, *outp; inp = fopen("bulat.dat", "r"); outp = fopen("bulat.out", "w"); fscanf(inp,"%lf", &radius); area = PI*radius*radius; circumference = 2*PI*radius; fprintf(outp,"Radius of a circle is %0.2f\n", radius); fprintf(outp,"Area of the circle is %0.2f\n", area); fprintf(outp,"circumference of the circle is %0.2f", circumference); fclose(inp); fclose(outp); return 0; } Open file to read Open file to write Use file Close 2 files
Created automatically by program Closing Files - example Created automatically by program Created by programmer
Exercise Week 6_5 Refer to Exercise 4 No. 1-4 in pg. 58. Solve the problem
Thank You Q & A