8.5 String Input
Reading text from standard input or a text file is very common in computer programs. The C programming language provides several functions for reading strings, which we explore in this section.
The scanf and fscanf functions can be used to read string input from standard input or a text file. To read text you must create a character array that is large enough to store the length of the expected input plus the null character:
- const int FILENAME_SIZE; // the const variable should be placed above main.
- char filename[FILENAME_SIZE] = "";
Then read the string in a fashion similar to how you read integers and floating-point values. There are two main differences, however. To read a string, you must use the %s format specifier and you do not include the & sign when passing the name of the array to the input function:
- printf("Enter the input file name: ");
- scanf("%s", filename);

The scanf function can not perform range checking on the array passed to store the string. Thus, it is important that you ensure the array is large enough to store the expected input.
The two scan functions can only be used to read "words" of text. As you learned earlier, the scanf and fscanf functions skip over white space before they begin reading input. When reading text, both functions stop reading text when the next character is whitespace (i.e. blank space, newline, tab, carriage return) or the end of file. For example, suppose you need to read a student's name from the user:
- const int NAME_SIZE = 20;
- char name[NAME_SIZE];
- printf("Enter student name: ");
- scanf("%s", name);
and enter the following text at the prompt:
John Smith
The scanf function will read "John" and then stop once it encounters the blank space
The rest of the input text will remain in the input buffer until the scanf function is
called again.
Program: countwords.cc
|