Write your own version of the Unix tool wc: count the lines, words and characters of its input. A word is a run of characters that are not spaces, tabs or newlines. Every character counts, including spaces and newlines.
Input
Any text, up to 10,000 characters. Every line ends with a newline.
Output
LINES WORDS CHARACTERS
Examples
Example 1 · Input
the cat sat on the mat
Expected output
2 6 23
Example 2 · Input
hello
Expected output
1 1 6
Hints
Hint 1
Read one character at a time with getchar() until it returns EOF.
Hint 2
A word starts at a character that is not a space when the one before was a space (or there was none).
Hint 3
isspace() from <ctype.h> is true for spaces, tabs and newlines.
Solution
Show one correct solution (try it yourself first)
#include <ctype.h>
#include <stdio.h>
int main(void) {
int c, lines = 0, words = 0, chars = 0, inWord = 0;
while ((c = getchar()) != EOF) {
chars++;
if (c == '\n') lines++;
if (isspace(c)) {
inWord = 0;
} else if (!inWord) {
inWord = 1;
words++;
}
}
printf("%d %d %d\n", lines, words, chars);
return 0;
}