Chapter 3 Input and Output C Programming for Scientists & Engineers with Applications by Reddy & Ziegler 3.1 Input and Output Functions Formatted Input and Output Functions Standard Input Function Standard Output Function Standard Input Function For input from the keyboard: scanf(“format control string”, &var1, &var2, ..., &varn); or For input from an input data file: fscanf(stdin, “format control string”, &var1, &var2,…, &varn); Programming Rule: The addresses of the input variables must be specified in the scanf() function. Reading Data From the Keyboard scanf (“%f %lf”, &income, &expense); Pass these auguments to scanf Convert the first keyboard data to a float type value and store the value in memory cell reserved for the variable income. Conversion specifications Note that %lf is for a double value The addresses of the variables, income and expense Use the “address of” operator, &, to pass the addresses of variables to functions Using scanf() for input And then saved in a float type variable income And then saved in a double type variable expense scanf(“ %f %lf ”, &income, &expense ); Will be converted to float type using %f First keyboard input Will be converted to double type using %lf Second keyboard input Double type variable Address of double type variable Operation of scanf function Keyboard input Value expressed as int or float value scanf scanf statement In source code Addresses of memory cell and way to store the value Value in correct memory cell Standard Output Function For output to the monitor or printer: printf(“format control string”, var1, var2, var3,…, varn); or For output to an output data file fprintf(stdout, “ format control string”, var1, var2, var3,…, varn); Sample C Program 2.5.1 sample code /*******************************************************/ /* */ /* THIS IS THE FIRST COMPLETE C PROGRAM */ /* */ /*******************************************************/ 1. #include <stdio.h> 2. int main() 3. { 4. int x, y, sum; 5. x = 5; 6. y = 6; 7. sum = x + y; 8. printf("x = %d y = %d sum = %d\n", x, y, sum); 9. return 0; 10.} For input and output the format control specifications for the built-in data types are: For data type int : For data type float : For data type double : For data type char : For data type character string : %d %f %lf or %e %c %s 3.2 File Input and Output Declaration of File Pointers open and close Statements Input from a Data File Output to a Data File Declaration of File Pointers A file pointer for input and output files must be declared. The declaration of the file pointers are as follows: FILE *inptr, *outptr; The word FILE must be in uppercase letters; you cannot use lowercase letters. The file pointer name must be preceded by an asterisk(*). Input and output data files For input: inptr = fopen(“inputfile.dat” , “r”); For output: outptr = fopen(“outputfile.dat” , “w”); Close data files fclose(inptr); fclose(outptr); There are several options other than “r” and “w” for file operations listed in the text. Input from an input data file fscanf(inptr , “format control string”, &var1, &var2, &var3, ……..,&varn); Instead of scanf for standard input, use fscanf for input from a data file. The first parameter must be the input file pointer. Reading Data From A File What function is most commonly used to read data from a file? fscanf(file_pointer, format_string, argument_list); Read the content of the file by file_pointer according to the conversion specifications in format_string The contents read are put into the addresses given by the argument_list. fscanf(inptr, “%d %lf”, &kk, &xx); The functions scanf and fscanf are closely related. Reading Data From A File What is a file pointer? A file pointer is a variable whose memory cell contains an address, which gives the key to accessing the file stored on disk. FILE *inptr; What is the convention for naming file pointers? The same as naming conventions for C identifiers Reading Data From A File What is FILE? A type set up for holding information about disk files C derived data type in the header file stdio.h, which must be included to use FILE Use the data type FILE to declare a file_pointer and use this file_pointer to handle your file FILE file_pointer FILE “L3_6.IN”; (Wrong!!) actual file Reading Data From A File How to open and close the file? Use the C library function fopen( ) to create a link between a disk file and a file pointer. file_pointer = fopen(file_name, access_mode); inptr = fopen(“C3_6.IN”, “r”); “r” means the file is opened for reading in text mode. Use fclose( ) function to close a file manually. fclose(file_pointer); Run source code Source Code #include <stdio.h> void main(void) { double xx ; int ii, kk; FILE *inptr; inptr = fopen ("C3_6.IN","r"); fscanf(inptr, "%d", &ii); fscanf(inptr, "%d %lf", &kk, &xx); fclose(inptr); printf("ii = %5d\n kk = %5d\n xx = %9.3lf\n",ii, kk, xx); } Output to an output data file fprintf(outptr , “format control string”, var1, var2, var3, ……..,varn); Instead of printf for standard output, use fprintf for output to a data file. The first parameter must be the output file pointer as shown Writing Output to A File Topics Writing data to a file Using the fprintf( ) function Previous programs have displayed all their output on the screen. May be convenient Once the screen scrolls or cleans, the output is lost Writing Output to A File An output file, Can have any acceptable file name Must be linked with a file pointer before it’s used. Must be open before it’s used Should be closed after it’s used Writing Output to A File What function is used to write data to a file? fprintf(file_pointer, format_string, argument_list) The fprintf( ) function writes the values of argument_list using the given format_string to a file that is linked to the program with the file pointer of file_pointer. fprintf(myfile, “week=%5d\n year=%5d\n”, week, year); The function fprintf is closely related to printf (like fscanf being related to scanf) Operations of fprintf Function Call to fprintf in source code File pointer Indicating disk file Conversion specification Variable names My file %7.2lf income Variable Value with formatting fprintf Disk file indicated by file pointer Writing Output to A File What function is used to open an output file and to create a link between the file pointer and file? Before data can be written to an external file, the file must be opened using the fopen( ) function file_pointer = fopen(file_name, access_mode); myfile = fopen(“L3_8.OUT”, “w”); Use the fclose( ) function to close an output file Run source code Writing Output to A File #include <stdio.h> void main(void) { double income=123.45, expenses=987.65; int week=7, year=1996; FILE *myfile; myfile = fopen("L3_8.OUT","w"); fprintf(myfile,"Week = %5d\n Year = %5d\n",week,year); fprintf(myfile,"Income = %7.2lf\n Expenses = %8.3lf\n", income,expenses); fclose(myfile); } 3.3 Filed Width Specification Input Field Width Specification Output Field Width Specification Field Width Specification In the format control string, the field width for each of the control fields can be specified for both input and output. The specification of field width to align the output data properly is very important, because the alignment increases the readability of output displayed on the monitor, printed, or written to a data file. %nd for integers %nd for integers, where n must be a numeric literal which specifies the format field width for locating integers to input. Examples are as follows: %7d %10d %12d These specifications provide 7 spaces, 10 spaces, and 12 spaces, respectively, for three integer numbers. %nf for real numbers %nf for real numbers, n must be a numeric literal which specifies the number of total decimal digits to be input possibly including a leading sign and a decimal point. %8f %10f These specifications mean the decimal numbers with sign and decimal point are found within the next 8 and 10 positions example With the field width specification %8.2f, the spaces are allocated as follows: 2 spaces for the fractional digits 1 space for the decimal point 1 space for the sign 4 spaces for the whole digits 3.4 Input and Output of Characters Standard Input and Output File Input and Output Unformatted Input and Output Input and Output of Characters Characters are stored internally in a code such as ASCII. The ASCII code for characters is presented in Appendix A. Each character is allocated one byte of storage. One byte of memory can hold decimal numbers in the range of 0 to 255. Therefore one byte of storage is enough to store 256 different character codes. Character variables are declared using the basic data type char Standard input of characters scanf(“%c%c%c”, &chr1, &chr2, &chr3); assume data is xyz There are no blank spaces in XYZ because there are no blank spaces in the format control string in the input statement. Notice that %c is the format control string for character data. standard output of characters printf(“%c %c %c”, chr1, chr2, chr3); The output is as follows: X Y Z If the format string is %d instead %c: printf(“%d %d %d”, chr1, chr2, chr3); The output is as follows: 88 89 90 Input from a data file FILE *inptr; char chr1, chr2, chr3, chr4; inptr = fopen(“infile.dat”, “r”); fscanf(inptr, “%c%c%c%c”, &chr1, &chr2, &chr3, &chr4); The input data is as follows: 3 XY stored in memory as: Output of character data to an output data file FILE *outptr; outptr = fopen(“outoutfile.dat”, “w”): char chr1 = ‘3’, chr2 = ‘ ‘, chr3 = ‘X’, chr4 = ‘Y’; fprintf(outptr, “%c%c%c%c”, chr1, chr2, chr3, chr4); The output is as follows: 3 XY 3.5 Sample Programs Conversion from Polar to Cartesian Coordinates Cost of a Steel Cage Convection Heat Transfer Air Conditioners Sales Report Wavelength of Electron