Character I/O

Textbook Background

The C standard library gives specialized means to read characters and strings, explicitly, as described in the following textbook sections.

Readings Characters and Strings

C provides two equivalent approaches for reading individual characters.

When reading character data with either getchar or %c with scanf, the first character is read and recorded; that is, the process of reading a character does NOT skip over white space.

Some of you may have noticed that we declared an int variable for reading using getchar. This is because every binary value in the char type is mapped to some sort of character encoding. However, when performing I/O, we need extra codes to indicate the end of file or an error. Thus, the value EOF fits in an int, but not a char, and may be used to determine whether the end of file been reached or an error has occurred, particularly when we are reading input from a file stored on disk, rather than from the terminal.

If valid data is read into ch, when a char is expected, the compiler will often translate the int with a simple cast for you.

Reading Strings

C also provides at least three approaches for reading strings of characters. Each function has its own special characteristics.

As with reading character data, stored input starts immediately with the first character read; the process of reading a string does NOT skip over white space.

Warning: Both scanf with the simple "%s" format and gets read characters (until white space or the end of a line), without regard for the size of the string array. If more characters are read than fit in the array, the characters may overflow memory to fill data stored in other variables. Thus, only fgets, getchar, and scanf with the "%Ns" format can be considered safe.