summaryrefslogtreecommitdiff
path: root/ex1-13.c
blob: 87fe0b06fda4dfc8ba5cd5a56acd6f5164c91b8d (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
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);
}