
10/6/2015 C Input/Output stdin, stdout, stderr C opens three input/output devices automatically: stdin The "standard input" device, usually your keyboard C Language II stdout The "standard output" device, usually your monitor stderr The "standard error" device, usually your monitor CMSC 313 Sections 01, 02 Some C library I/O functions automatically use these devices Adapted from Richard Chang, CMSC 313 Spring 2013 Adapted from Richard Chang, CMSC 313 Spring 2013 1 10/6/2015 Formatted Console Output printf( ) Conversions Common printf( ) Conversions • printf( ) outputs formatted text to stdout Conversions specifications begin with % and end with a Spec Conversion performed conversion character. %d print integer as a decimal number (base 10) printf( format, arg1, arg2, … ); Between the % and the conversion character MAY be, in %u print integer as unsigned number order A minus sign specifying left-justification • Example: %s print string int n = 3 ; The minimum field width printf (“Value = %d\n”, n) ; A period separating the field width and %f print double as a floating point number precision The precision that specifies %x print integer in hexadecimal (base 16) Maximum characters for a string • format is a string containing Number of digits after the decimal for a floating %c print integer as ASCII character • conversion specifications point Minimum number of digits for an integer • literals to be printed %p An h for "short" or an l (letter ell) for long print pointer in hexadecimal (implementation dependent) man printf for more documentation. Adapted from Richard Chang, CMSC 313 Spring 2013 Adapted from Richard Chang, CMSC 313 Spring 2013 Adapted from Richard Chang, CMSC 313 Spring 2013 2 10/6/2015 printf( ) Examples Formatted Output Example Keyboard Input • scanf reads user input from stdin. int anInt = 5678; double aDouble = 4.123; Use field widths to align output in columns • Syntax for scanf( ) is similar to printf( ) scanf( int i; #define NAME "Bob" format, arg1, arg2, ... ) for (i = 1 ; i < 5; i++) printf("%2d %10.6f %20.15f\n", i, sqrt(i), sqrt(i)); • The format string similar structure to printf( ). /* what is the output from each printf( ) */ printf("%d is a large number\n", anInt); • The arguments must be addresses of the variables. 12 1234567890 12345678901234567890 printf("%8d is a large number\n", anInt); 1 1.000000 1.000000000000000 printf("%-8d is a large number\n", anInt); 2 1.414214 1.414213562373095 printf("%10.2f is a double\n", aDouble); 3 1.732051 1.732050807568877 printf("The sum of %d and %8.4f is %12.2f\n", 4 2.000000 2.000000000000000 anInt, aDouble, anInt + aDouble); printf ("Hello %s\n", NAME); Adapted from Richard Chang, CMSC 313 Spring 2013 Adapted from Richard Chang, CMSC 313 Spring 2013 Adapted from Richard Chang, CMSC 313 Spring 2013 3 10/6/2015 scanf( ) Format String Common scanf( ) Conversions scanf( ) Examples Spec Conversion performed • The scanf( ) format string usually contains int age; %d a decimal (integer) number conversion specifications that tell scanf( ) how to double gpa; interpret the next "input field". An input field is a %u An unsigned decimal (integer) number char initial; string of non-whitespace characters. %x a hexadecimal number • The format string usually contains: printf("input your middle initial: "); %f – Blanks or tabs which are ignored a floating point number with optional sign, scanf("%c", &initial); // Note & decimal point, and exponent – Ordinary characters which are expected to match the next printf("Input your age: "); (non- whitespace) character input by the user %s a string delimited by white space, NOT an scanf("%d", &age); – Conversion specifications usually consisting entire line printf("input your gpa: "); • % character indicating the beginning of the conversion %c a single character (possibly a whitespace char) scanf("%lf", &gpa); • An optional h, l (ell) or L • A conversion character which indicates how the input field is to be interpreted. Adapted from Richard Chang, CMSC 313 Spring 2013 Adapted from Richard Chang, CMSC 313 Spring 2013 Adapted from Richard Chang, CMSC 313 Spring 2013 4 10/6/2015 Unix I/O redirection Text File I/O fopen() • Redirect input (read from infile instead of keyboard): a.out < infile • Use fprintf() and fscanf() functions instead of fopen( ) requires two parameters printf() and scanf(). 1. The name of the text file to be opened • Redirect output (write to outfile instead of screen): • Must open file before reading/writing: fopen() a.out > outfile 2. The text file open "mode" • Must close file after all done: fclose() “r” open the file for reading only • Redirect both: • Use file handle to specify file. “w” create the file for writing; delete existing file a.out < infile > outfile • File handle returned by fopen(): “a” append; open or create the file for writing at the end FILE *myFile ; • Redirect stdout and stderr to outfile “r+” open the file for reading and writing myFile = fopen (“bob.txt”, “r”) ; a.out >& outfile if (myFile == NULL) { “w+” create the file for reading & writing; deletes existing file /* handle the error */ “a+” open or create the file for reading or writing at the end • Redirect stdout to outfile and stderr to errfile } (a.out > outfile) >& errfile Adapted from Richard Chang, CMSC 313 Spring 2013 Adapted from Richard Chang, CMSC 313 Spring 2013 Adapted from Richard Chang, CMSC 313 Spring 2013 5 10/6/2015 fscanf.c Detecting end-of-file with fscanf EOF Example Code #include <stdio.h> #include <stdlib.h> /* for “exit” */ • When reading an unknown number of data elements from a /* code snippet that reads an undetermined number of int main ( ) file using fscanf( ), we need a way to determine when integer student ages from a file and prints them out { the file has no more data to read, i.e, we have reached the as an example of detecting EOF (scanfEOF.c) double x ; "end of file". */ FILE *ifp ; FILE *inFile; int age; /* try to open the file for reading, check if successful */ /* if it wasn't opened exit gracefully */ • Fortunately, the return value from fscanf( ) holds the ifp = fopen("test_data.dat", "r") ; key. fscanf( ) returns an integer which is the number inFile = fopen( “myfile”, “r” ); if (ifp == NULL) { of data elements read from the file. If end-of-file is if (inFile == NULL) { printf ("Error opening test_data.dat\n"); detected the integer return value is the special value EOF printf ("Error opening myFile\n"); exit (-1); exit (-1); } } fscanf(ifp, "%lf", &x) ; /* read one double from the file */ fclose(ifp); /* close the file when finished */ while ( fscanf(inFile, “%d”, &age ) != EOF ) /* check to see what you read */ printf( “%d\n”, age ); printf("x = %.2f\n", x) ; return 0; fclose( inFile ); } Adapted from Richard Chang, CMSC 313 Spring 2013 Adapted from Richard Chang, CMSC 313 Spring 2013 Adapted from Richard Chang, CMSC 313 Spring 2013 6 10/6/2015 fprintf.c Characters & Strings char Type /* fprintf.c */ • C supports the char data type for storing a single #include <stdio.h> #include <stdlib.h> /* exit */ character. int main ( ) { • char uses one byte of memory double pi = 3.14159 ; FILE *ofp ; • char constants are enclosed in single quotes /* try to open the file for writing, check if successful */ char myGrade = ‘A’; /* if it wasn't exit gracefully */ char yourGrade = ‘?’; ofp = fopen("test.out", “w") ; if (ofp == NULL) { printf ("Error opening test.out\n"); exit (-1); } /* write to the file using printf formats */ fprintf(ofp, “Hello World\n”); fprintf(ofp, “PI is defined as %6.5lf\n”, pi); fclose(ofp); /* close the file when finished reading */ return 0; } Adapted from Richard Chang, CMSC 313 Spring 2013 Adapted from Richard Chang, CMSC 313 Spring 2013 Adapted from Richard Chang, CMSC 313 Spring 2013 7 10/6/2015 Special Characters Special Char Example Code Character Library Functions Use \ for escape sequences. • What is the output from these statements? int isdigit (int c); Determine if c is a decimal digit (' 0' - ' 9' ) For example printf("\t\tMove over\n\nWorld, here I come\n"); int isxdigit(int c); \n is the newline character Determines if c is a hexadecimal digit (' 0' - ' 9' , ' a' - f' , or ' A' - ' F' ) \t is the tab character Move over int isalpha (int c); \" is the double quote (necessary since double quotes are used to enclose strings Determines if c is an alphabetic character (' a' - ' z' or ' A- ' Z' ) World, here I come \' is the single quote (necessary since single quotes are int isspace (int c); used to enclose chars Determines if c is a whitespace character (space, tab, etc) printf("I\' ve written \"Hello World\"\n\t many times\n\a"); \\ is the backslash (necessary since \ now has special int isprint (int c); meaning Determines if c is a printable character \a is beep which is unprintable I' ve written "Hello World“ many times int tolower (int c); <BEEP> int toupper (int c); Returns c changed to lower- or upper-case respectively, if possible Adapted from Richard Chang, CMSC 313 Spring 2013 Adapted from Richard Chang, CMSC 313 Spring 2013 Adapted from Richard Chang, CMSC 313 Spring 2013 8 10/6/2015 Character Library Functions Character Input/Output Strings in C • Use %c in printf( )and fprintf( )to output a single • String = null terminated array of char. Include header file use character library functions: character. char yourGrade = ‘A’; • null = '\0' #include <ctype.h> printf( “Your grade is %c\n”, yourGrade); • String constants in double quotes are null terminated. Technically functions take an int parameter, not char. • Input char(s) using %c with scanf( ) or fscanf( ) • Strings do not "know" their own length. Return type is also int . 0 = False, not 0 = True. char grade, scores[3]; • Initialization: char name4[20] = {‘B’, ‘o’, ‘b’, ‘b’, ‘y’, ‘\0’}; – %c inputs the next character, which may be whitespace man ctype.h for more functions and complete documentation.
Details
-
File Typepdf
-
Upload Time-
-
Content LanguagesEnglish
-
Upload UserAnonymous/Not logged-in
-
File Pages18 Page
-
File Size-