summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authormartin@ashbysoft.com <martin@ashbysoft.com>2022-06-12 17:41:24 +0000
committermartin@ashbysoft.com <martin@ashbysoft.com>2022-06-12 17:41:24 +0000
commit5506047efd5cde023e793b437ede1328054a0890 (patch)
treea48731eb164c3ae0968f0b3a5522a9fbdfd820af
parentbb40c4cbc74fe48a04069e6efb78c94bd0cc0451 (diff)
downloadlearn-c-5506047efd5cde023e793b437ede1328054a0890.tar.gz
learn-c-5506047efd5cde023e793b437ede1328054a0890.tar.bz2
learn-c-5506047efd5cde023e793b437ede1328054a0890.tar.xz
learn-c-5506047efd5cde023e793b437ede1328054a0890.zip
ex1-13
-rw-r--r--ex1-13.c64
1 files changed, 64 insertions, 0 deletions
diff --git a/ex1-13.c b/ex1-13.c
new file mode 100644
index 0000000..87fe0b0
--- /dev/null
+++ b/ex1-13.c
@@ -0,0 +1,64 @@
+#include <stdio.h>
+#include <stdint.h>
+#include <stdbool.h>
+
+#define max_word 100
+
+typedef enum _state {in,out} state;
+bool is_word(char c) {
+ return c != ' '
+ && c != '\t'
+ && c != '\n';
+}
+/* print a histogram of word lengths
+ read from input
+ print histo to output
+ print errors warnings to output_err */
+int whisto(FILE* input, FILE* output, FILE* output_err) {
+ uint32_t lens[max_word]={0};
+ int c = fgetc(input);
+ if (c == EOF) {
+ fprintf(output_err, "warning: no input!\n");
+ goto spout;
+ }
+ state s = is_word(c) ? in : out;
+ uint32_t cl = s == in ? 1 : 0;
+ while ((c = fgetc(stdin))!= EOF){
+ if (is_word(c)){
+ if (s == in) {
+ cl++;
+ } else {
+ s = in;
+ cl=1;
+ }
+ } else {
+ if (s == in) {
+ s = out;
+ lens[cl]++;
+ } else {
+ // do nothing I guess
+ }
+ }
+ }
+ // need to count final word
+ if (s == in) {
+ lens[cl]++;
+ }
+spout:
+ for(uint16_t i=1;
+ i<max_word;
+ i ++) {
+ fprintf(output, "%2d: ",i);
+ for(uint16_t j=0;
+ j<lens[i];
+ j++)
+ fputc('-', output);
+ fputc('\n', output);
+ }
+ return 0;
+}
+
+int main(void){
+ whisto(stdin, stdout, stderr);
+}
+ \ No newline at end of file