diff options
author | Michael Hunteman <michael@huntm.net> | 2023-07-04 17:03:53 -0500 |
---|---|---|
committer | Michael Hunteman <michael@huntm.net> | 2023-07-06 17:23:45 -0500 |
commit | bfce8f0d0d828209ec0bec71371ee94a7ad62d3e (patch) | |
tree | bdf49ca788ca1ca030d5b1cccfd0c9dffeb3f69f /one/char.c |
Initial commit
Diffstat (limited to 'one/char.c')
-rw-r--r-- | one/char.c | 53 |
1 files changed, 53 insertions, 0 deletions
diff --git a/one/char.c b/one/char.c new file mode 100644 index 0000000..91cfc75 --- /dev/null +++ b/one/char.c @@ -0,0 +1,53 @@ +#include <stdio.h> + +#define IN 1 /* inside of a word */ +#define OUT 0 /* outside of a word */ + +/* count lines, words, and characters */ +void +wc() +{ + /* + * c must be big enough to hold any value getchar() returns so we use + * int instead of char to hold EOF, an integer defined in stdio + */ + int c, nl, nw, nc, state; + state = OUT; + nl = nw = nc = 0; + while ((c = getchar()) != EOF) { + ++nc; + if (c == '\n') { + ++nl; + } + /* && is higher precedence than || */ + if (c == ' ' || c == '\t' || c == '\n') { + state = OUT; + } else if (state == OUT) { + state = IN; + ++nw; + } + } + printf("%d %d %d\n", nl, nw, nc); +} + +/* print input separated by new lines */ +void +print_word_line() +{ + int c; + while ((c = getchar()) != EOF) { + if (c == ' ' || c == '\t' || c == '\n') { + putchar('\n'); + } else { + putchar(c); + } + } +} + +int +main() +{ + wc(); + /* print_word_line(); */ + return 0; +} |