Programming in C

(Barry) #1
Variable-Length Character Strings 215

else
totalWords += countWords (text);
}

printf ("\nThere are %i words in the above text.\n", totalWords);

return 0;
}

Program 10.8 Output
Type in your text.
When you are done, press 'RETURN'.

Wendy glanced up at the ceiling where the mound of lasagna loomed
like a mottled mountain range. Within seconds, she was crowned with
ricotta ringlets and a tomato sauce tiara. Bits of beef formed meaty
moles on her forehead. After the second thud, her culinary coronation
was complete.
Enter
There are 48 words in the above text.

The line labeled Enterindicates the pressing of the Enter or Return key.
The endOfTextvariable is used as a flag to indicate when the end of the input text
has been reached.The whileloop is executed as long as this flag is false. Inside this
loop, the program calls the readLinefunction to read a line of text.The ifstatement
then tests the input line that is stored inside the textarray to see if just the Enter (or
Return) key was pressed. If so, then the buffer contains the null string, in which case the
endOfTextflag is set to trueto signal that all of the text has been entered.
If the buffer does contain some text, the countWordsfunction is called to count the
number of words in the textarray.The value that is returned by this function is added
into the value of totalWords, which contains the cumulative number of words from all
lines of text entered thus far.
After the whileloop is exited, the program displays the value of totalWords, along
with some informative text, at the terminal.
It might seem that the preceding program does not help to reduce your work efforts
much because you still have to manually enter all of the text at the terminal. But as you
will see in Chapter 16, “Input and Output Operations in C,” this same program can also
be used to count the number of words contained in a file stored on a disk, for example.
So, an author using a computer system for the preparation of a manuscript might find
this program extremely valuable as it can be used to quickly determine the number of
words contained in the manuscript (assuming the file is stored as a normal text file and
not in some word processor format like Microsoft Word).

Program 10.8 Continued

TEAM FLY

Free download pdf