The getchar
function obtains
integer-cast characters from keyboard input or input redirected from a
file; the putchar
function displays characters. If
getchar
encounters an error or the end of a file, it returns
whatever value the macro EOF
expands to, which is
-1
in most implementations. The following program, an
iterative filter, converts lower-case letters to upper-case letters,
because each upper-case letter, viewed as an integer, is
equally offset from the corresponding lower-case letter:
#includeint transform_letter (int arg) { int offset = 'A' - 'a'; if ((int) 'a' <= arg && arg <= (int) 'z') return arg + offset; else return arg; } main ( ) { int input; while (EOF != (input = getchar ( ))) putchar (transform_letter (input)); }
Note that getchar
casts input characters into integers of
type int
, thereby requiring a cast at the point where those
characters are compared with character constants.