Count Lines, Words, and Characters

Let's have more practice with the while loop that reads all characters till the end of input:

int c;

while ((c = getchar()) != EOF) {
	...
}

Let's write code that will mimic the behavior of the wc command line tool (in Linux or macOS). It reads its input and prints three numbers: how many lines there are in the input, how many words, and how many characters.

There are some special cases that need to be taken care of:

The trickiest part here is to count words. You will probably need to have a separate variable to track if the word you are reading was already counted, or not.

I'll give you a skeleton program which prints three numbers!

#include <stdio.h>

int main() {
	int lines = 0, words = 0, characters = 0;

	/* TODO: your code here */

	printf("%d %d %d\n", lines, words, characters);
	return 0;
}

After you figure this out, we'll talk more about reading from the input!

© Alexander Fenster (contact)