A Word-Count Program
Now you have the tools to make a word-counting program, that is, a program that reads input and reports the number of words it finds. You may as well count characters and lines while you are at it. Let's see what such a program involves.
First, the program should read input character-by-character, and it should have some way of knowing when to stop. Second, it should be able to recognize and count the following units: characters, lines, words. Here's a pseudocode representation:
read a character while there is more input increment character count if a line has been read, increment line count if a word has been read, increment word count read next character
You already have a model for the input loop:
while ((ch = getchar()) ...
Get C Primer Plus®, Third Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.