diff options
Diffstat (limited to 'ch01/ex11-wc.c')
| -rw-r--r-- | ch01/ex11-wc.c | 35 |
1 files changed, 35 insertions, 0 deletions
diff --git a/ch01/ex11-wc.c b/ch01/ex11-wc.c new file mode 100644 index 0000000..e2ec1d8 --- /dev/null +++ b/ch01/ex11-wc.c @@ -0,0 +1,35 @@ +#include <stdio.h> + +#define IN 1 /* inside a word */ +#define OUT 0 /* outside a word */ + +/* count lines, words, and characters in input + * + * I would focus on testing the state transitions, since character and + * line counting are straightforward. The character count increments for + * every character that is not EOF, and the line count increments whenever + * a newline is encountered. Word counting is more complex because it + * depends on correctly detecting boundaries. I would include test cases + * with varying numbers of spaces, tabs, and newlines to verify that word + * boundaries are handled correctly, since those inputs are the most likely + * to reveal bugs. + */ +int main() +{ + int c, nl, nw, nc, state; + + state = OUT; + nl = nw = nc = 0; + while ((c = getchar()) != EOF) { + nc++; + if (c == '\n') + ++nl; + if (c == ' ' || c == '\n' || c == '\t') + state = OUT; + else if (state == OUT) { + state = IN; + ++nw; + } + } + printf("%d %d %d\n", nl, nw, nc); +} |
