Console Input and Output Hour 5 PObjectives <C I/O < Character I/O: getchar, putchar, and getch < printf format specifiers field width and precision justification and padding < scanf Copyright 1998-2002 Delroy A. Brinkerhoff. All Rights Reserved. Hour 5 C Slide 1 of 12 Introduction to C I/O Console and file I/O PI/O is the first topic where C++ diverges from C <All C I/O is available in C++ (and can be used in the same program) < C++ introduces many intelligent objects to handle I/O PI/O is implemented through library functions (not operators) PStandard I/O library is declared in <stdio.h> PConsole I/O is a special case of file I/O < In Unix, devices (screen, keyboard, etc.) are files < All C programs begin with three files pre-opened standard in (keyboard) standard out (screen) standard error (screen) PConsole I/O functions only perform tty I/O (i.e., no windows) Hour 5 C Slide 2 of 12
Character Input Reading one character at a time Pint getchar(void) < Returns a single character from the keyboard (stdin) < Character not read until the enter key is pressed (implementation defined but almost always based on Unix line-buffered input) <Returns EOF (< 0, usually -1) on error or if control-d (Unix) or control-z (DOS, Borland and Win95) is entered <Should be assigned to an int variable (EOF is often -1) PCommon idiom: int c;.. while ((c = getchar())!= EOF) /* process character c */ Hour 5 C Slide 3 of 12 The getchar Problem Illustrated A potential pitfall #include <stdio.h> int main(void) { int c; while ((c = getchar( ))!= EOF) /* end with a ^D (Unix) or ^Z (DOS) */ { getchar( ); /* discard new-line from enter key */ } switch(c) { case 'a' : puts("a\n"); break; case 'b' : puts("b\n"); break; case 'c' : puts("c\n"); break; case '\n' : puts("new line\n"); break; } return 0; } Hour 5 C Slide 4 of 12
Character Output Writing one character at a time Pint putchar(int c) <Writes a single character to the screen (stdout) <Only the low-order byte is printed <Return value: c on success; EOF on failure < Less overhead than printf <Return EOF on error, c if otherwise PExample: char* message = hello world ; int i; for (i = 0; i < 11; i++) putchar(message[i]); Hour 5 C Slide 5 of 12 Single-Character Input Functions Non-standard (i.e., not ANSI) functions PReads the character but does not echo the character < int getch(void); Borland / Unix < int _getch(void); Microsoft PReads the character and echos it to the screen < int getche(void); Borland / Unix < int _getche(void); Microsoft PDoes not require a new line (pressing the enter key) PPrototype in <conio.h> (Borland and Microsoft) PPart of the Unix curses library (<curses.h> and -lcurses) PSee getch.c for a simple Unix implementation Hour 5 C Slide 6 of 12
printf Formatted output PPrototype in <stdio.h> Pint printf("controlstring", arg1, arg2, arg3...); < The controlstring is required; other arguments are optional < The return value (the number of characters printed or a negative value on error) is almost never checked PExcess arguments (no corresponding format specifier) are ignored; format specifiers without corresponding arguments produce undefined results PArguments may be any legal expression printf( The answer is: %d and %d\n, ans1, ans2); Hour 5 C Slide 7 of 12 The Control String Output specification PContains < Characters that are printed without modification < Format specifiers: minimally a percent sign (%) & a conversion specifier (see page 79 or a list of conversion specifiers) PFormat specifiers <% position flag fieldwidth precision length conversion <Position integer $ position in the argument list of the next arguments to be converted < Flag (dash, hyphen, or minus sign) left justify output (used w/ field width) 0 (zero) pad with 0 s (default is pad with blanks) + precede numbers with + or - (blank or space) precede numbers with space or - Hour 5 C Slide 8 of 12
The Control String Continued PfieldWidth < integer > 0 minimum field width, excess space filled w/ pad char < * takes the next argument for width specifier < printf("%4d", counter); Pprecision <. integer number of digits following the decimal point <.* takes the next argument for precision specifier < printf("%6.2f", pay); /* 3 digits before the decimal, two after */ Plength < l (lower case L) used with d, i, o, u, x, and X; specifies a long value (effect is implementation dependent) < printf("%lf", doublevalue); Hour 5 C Slide 9 of 12 Simple printf Examples Common usage printf( %d %7d %10d, 10, counter, 10+counter); printf( i*pi = %f sin(i*pi) = %15.10f\n, i*pi, sin(i*pi)); printf( A = %d in ASCII\n, A ); printf( Can t open file \ %s\ \n, filename); printf( Test Score: %f6.2%%\n, tscore); printf( The Earth weighs %e tons, 6.65e24); Hour 5 C Slide 10 of 12
Data Input with scanf Standard library input function PUsed to read data from the keyboard P#include <stdio.h> (prototype, constants, etc.) PExcess arguments (no corresponding control character) are ignored. Control characters without corresponding arguments produce undefined results PArguments must be pointers (i.e., addresses); these are usually found with the address of operator (&) see Hour 11 scanf( %d, &ans1); Hour 5 C Slide 11 of 12 scanf Examples Basic Input with scanf int float double char size; balance; debt; answer; scanf( %d, &size); scanf( %f, &balance); scanf( %lf, &debt);/* must use l for double */ scanf( %c, &answer); Hour 5 C Slide 12 of 12