summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authormartin@ashbysoft.com <martin@ashbysoft.com>2022-06-11 21:25:01 +0000
committermartin@ashbysoft.com <martin@ashbysoft.com>2022-06-11 21:25:01 +0000
commit83e0861e200999ed46a1a1a8afa0b5638e48e14b (patch)
tree05cf8909e5c53c2b540f2b7aa71d0f12769001e9
parent62482c2d0d6b2080d51fe6ea03e2ccd93e3351e0 (diff)
downloadlearn-c-83e0861e200999ed46a1a1a8afa0b5638e48e14b.tar.gz
learn-c-83e0861e200999ed46a1a1a8afa0b5638e48e14b.tar.bz2
learn-c-83e0861e200999ed46a1a1a8afa0b5638e48e14b.tar.xz
learn-c-83e0861e200999ed46a1a1a8afa0b5638e48e14b.zip
ex1-9 ex1-10
-rw-r--r--ex1-10.c36
-rw-r--r--ex1-8.c3
-rw-r--r--ex1-9.c22
-rwxr-xr-xrun2
4 files changed, 61 insertions, 2 deletions
diff --git a/ex1-10.c b/ex1-10.c
new file mode 100644
index 0000000..0b0c018
--- /dev/null
+++ b/ex1-10.c
@@ -0,0 +1,36 @@
+#include <stdio.h>
+#include <stdint.h>
+#include <stdbool.h>
+
+/* Track whether we are inside or outside a word */
+typedef enum _state {IN,OUT} state;
+
+/* true if c is a 'word' character (not a blank, space, or a tab) */
+bool is_word(char c) {
+ return c != ' ' && c != '\t' && c != '\n';
+}
+
+/* Counts characters, lines, and words from stdin.
+
+ 'characters' are single byte characters. No handling for encodings in c standard lib.
+ 'lines' are newline characters.
+ 'words' are contiguous sequences of characters other than space, tab, newline */
+int main(void) {
+ int c;
+ state s = OUT;
+ uint32_t cc = 0, lc = 0, wc = 0;
+ while ((c = getchar()) != EOF) {
+ cc++;
+ if (c == '\n') {
+ lc++;
+ }
+ if (!is_word(c)) {
+ s = OUT;
+ } else if (s == OUT) {
+ s = IN;
+ wc++;
+ }
+ }
+ printf("cc=%d lc=%d wc=%d\n", cc, lc, wc);
+ return 0;
+} \ No newline at end of file
diff --git a/ex1-8.c b/ex1-8.c
index b692948..cc70b64 100644
--- a/ex1-8.c
+++ b/ex1-8.c
@@ -1,4 +1,5 @@
#include <stdio.h>
+#include <stdint.h>
int main(void) {
int c;
@@ -14,4 +15,4 @@ int main(void) {
}
printf("nl=%ld tb=%ld bl=%ld\n", nl, tb, bl);
return 0;
-} \ No newline at end of file
+}
diff --git a/ex1-9.c b/ex1-9.c
new file mode 100644
index 0000000..e7d4d25
--- /dev/null
+++ b/ex1-9.c
@@ -0,0 +1,22 @@
+#include <stdio.h>
+#include <stdbool.h>
+/* Copy stdin to stdout, replacing consecutive spaces with a single space
+ Edge case: a leading space is retained if there are leading spaces.
+ Edge case: an empty file just doesn't echo anything, but emits a warning on stderr */
+int main(void) {
+ int c = getchar();
+ if (c == EOF) {
+ fprintf(stderr, "warning: no input\n");
+ goto exit;
+ }
+ putchar(c);
+ bool bl = (c == ' ');
+ while ((c = getchar()) != EOF) {
+ if ((!bl) || (c != ' ')) {
+ putchar(c);
+ }
+ bl = (c == ' ');
+ }
+exit:
+ return 0;
+} \ No newline at end of file
diff --git a/run b/run
index 185f869..11c2851 100755
--- a/run
+++ b/run
@@ -4,4 +4,4 @@ cc -o exe $@
./exe
result=$?
rm exe
-exit $result \ No newline at end of file
+exit $result