CS 200 - Lab 14

Word count

Write a program to count the number of words that the user types.  For the purposes of this lab, a word is a sequence of non-whitespace characters.  As in Lab 13, the user will type Control-Z followed by Enter to signal the end of input.

Example run:

It is a truth universally acknowledged, that a single man in
possession of a good fortune, must be in want of a wife.
^Z
The input contained 23 words

Getting started

If you have a solution open in Visual Studio, close it (File->Close Solution).

Download lab14.zip.  Import it into Visual Studio (File->Import...).

Add your code to the source file called WordCount.c.

Hints

The program should contain a loop that looks like this:

while (!feof(stdin)) {
int ch;

ch = getchar();

if (ch >= 0) {
/* do something with the character value read */
}
}

If the last character value read is stored in the variable ch, the following condition returns true if ch contains a whitespace character:

isspace(ch)

A good approach to this problem is to use two variables: one to keep track of the number of words seen so far, and another to keep track of whether the last character read was part of a word or was a space.  After reading each character, determine whether or not the character was a whitespace character, and update the variables appropriately.