summaryrefslogtreecommitdiff
path: root/ch01/ex11-wc.c
diff options
context:
space:
mode:
authorZhineng Li <[email protected]>2026-01-10 16:37:39 +0800
committerZhineng Li <[email protected]>2026-01-10 16:37:39 +0800
commit49891f6bce29843f503b437c84d83cb787ecfa87 (patch)
tree50bd44422a907b869a6d4839df436f37a35be36d /ch01/ex11-wc.c
downloadc-knr-exercises-49891f6bce29843f503b437c84d83cb787ecfa87.tar.gz
c-knr-exercises-49891f6bce29843f503b437c84d83cb787ecfa87.zip
first commit
Diffstat (limited to 'ch01/ex11-wc.c')
-rw-r--r--ch01/ex11-wc.c35
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);
+}