Book
Collection
Click for Table of Contents
© 2025 by Rance D. Necaise
C Primer for Python Programmers
Copyright © 2025
Rance D. Necaise

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:

  1. const int FILENAME_SIZE;   // the const variable should be placed above main.
  2. 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:

  1. printf("Enter the input file name: ");
  2. scanf("%s", filename);
Warning
Warning

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:

  1. const int NAME_SIZE = 20;
  2. char name[NAME_SIZE];
  3.  
  4. printf("Enter student name: ");
  5. 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.

Listing 8.5.1
  1.  /* Counts and returns the number of words in a text file. We assume no
  2.     word in the file is larger than 127 characters in length. */
  3. int countWords(FILE *infile, int maxSize)
  4. {
  5.   char input[128];
  6.   int numWords = 0;
  7.  
  8.   fscanf(infile, "%s", input);
  9.   while(!feof(infile)) {
  10.     numWords++;
  11.     fscanf(infile, "%s", input);    
  12.   }
  13.  
  14.   return numWords;
  15. }
Program: countwords.cc