Skip to content
Laviyx Learn

Try

PPS Lab · Experiment 39

Count lines, words and characters in a text

CStringsJNTUH R22 · CS108ES

Aim

To write a C program that reads text from the keyboard until end of input and counts the number of lines, words and characters in it.

Algorithm

  1. Set lines, words and chars to 0, and set in_word to 0 (not inside a word).
  2. Read one character at a time with getchar until it returns EOF.
  3. Add 1 to chars for every character read, including spaces and newlines.
  4. If the character is a newline, add 1 to lines.
  5. If the character is a space, tab or newline, set in_word to 0. Otherwise, if in_word is 0, a new word has started: add 1 to words and set in_word to 1.
  6. At the end, if the text did not end with a newline, add 1 to lines for the last line.
  7. Print the three counts.

Program

C
#include <stdio.h>
#include <ctype.h>

int main(void) {
    int ch;
    int lines = 0, words = 0, chars = 0;
    int in_word = 0;      /* 1 while we are inside a word */
    int last = '\n';      /* the last character read */

    printf("Enter the text. End it with Ctrl+D (Linux) or Ctrl+Z and Enter (Windows):\n");
    while ((ch = getchar()) != EOF) {
        chars++;
        if (ch == '\n') {
            lines++;
        }
        if (isspace(ch)) {
            in_word = 0;          /* a space, tab or newline ends a word */
        } else if (in_word == 0) {
            in_word = 1;          /* first letter of a new word */
            words++;
        }
        last = ch;
    }
    if (last != '\n') {
        lines++;                  /* last line had no newline at its end */
    }

    printf("Lines = %d\n", lines);
    printf("Words = %d\n", words);
    printf("Characters = %d\n", chars);
    return 0;
}

Output

Output
Enter the text. End it with Ctrl+D (Linux) or Ctrl+Z and Enter (Windows):
C is a simple language.

It is fast  and   portable.
Lines = 3
Words = 10
Characters = 53

Recorded by compiling and running this exact program. Typed input appears after each prompt.

How it works

What is counted:

  • A character is every character read, including spaces, tabs and the newline at the end of each line.
  • A word is a group of characters with no space, tab or newline inside it. Several spaces in a row still separate just two words, as in the third line of the run.
  • A line is counted at each newline. A blank line counts as a line but has no words.

In the run, line 1 has 23 characters, line 2 is empty, and line 3 has 27 characters. With the three newlines that makes 23 + 0 + 27 + 3 = 53 characters. The words are 5 + 0 + 5 = 10.

To end the input, press Ctrl+D on Linux or macOS, or Ctrl+Z and then Enter on Windows. On Windows, Ctrl+Z works only at the start of a new line, so press Enter after the last line first.

Common mistakes

  • Storing the result of getchar in a char. EOF is an int value (usually −1) that must be told apart from every real character, so the variable must be an int.

  • Counting a word at every space. Two spaces in a row, or a space at the start of a line, then count extra words. Count a word only when a non-space character follows a space (the in_word flag).

  • Reading with scanf("%s"). It skips all spaces and newlines, so the program can no longer count lines or characters.

  • Pressing Ctrl+C to end the input. That stops the program before it prints anything. Use Ctrl+D (Linux) or Ctrl+Z then Enter (Windows).

Viva questions

Try to answer each one aloud before you open it.

  • What is EOF, and how do you send it from the keyboard?

    EOF (end of file) is a value, usually −1, that input functions return when there is no more input. From the keyboard it is sent with Ctrl+D on Linux and macOS, or Ctrl+Z followed by Enter on Windows.

  • Why is the in_word flag needed?

    It remembers whether the previous character was part of a word. A word is counted only when a word starts, so many spaces in a row do not add extra words.

  • What does isspace() check?

    isspace (from ctype.h) returns true for whitespace characters: space, tab, newline, carriage return, vertical tab and form feed.

  • Why does the program check the last character after the loop?

    If the text does not end with a newline, the last line has no newline to count, so one is added for it.

  • Which Linux command does the same job?

    wc (word count). wc file.txt prints the number of lines, words and bytes in the file.

Learn the concepts

All Programming for Problem Solving Lab experiments →