CSC 161 Grinnell College Fall, 2011
 
Imperative Problem Solving and Data Structures
 
 

Characters and Strings in C

Reading Character Data

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 Kernighan & Ritchie's book, The C Programming Language, declares int variables and sets them to char values, while the above examples declare char variables set to char values. The local system automatically converts the int values that getchar and getc into char values when set to a char variable, so on the local system, these declarations are valid. Just be aware that some systems may not support this automatic conversion.

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 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 to fill data stored in other variables. Thus, only fgets can be considered "safe".