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:
lines: we assume that the number of lines is equal to the number of new line characters
\nin the input. That means that if the input does not end with the new line character, its last line won't count.words: in this exercise, words are separated by spaces
' 'or new line characters\n. The input"abc abc"has two words, even though there are two spaces between them. In the real word it's even more complicated: the realwctool will check for all kinds of whitespace characters; we don't care about them in this exercise.characters: this is the most straightforward: calculate how many characters you have read before you encountered
EOF.
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!