#include <errno.h>
#include <stdio.h>

int main() {
  int total = 0;
  double acc = 0, val;

  for (;;) {
    fputs("Value: ", stdout);
    fflush(stdout);

    errno = 0;
    int res = fscanf(stdin, "%lf", &val);

    if (res == EOF) {
      // Handle successful end of input or read error.
      if (errno == 0) {
        fprintf(stdout, "Done! You entered %d values averaging %f.\n", total, acc / total);
      } else {
        fputs("There was an error, aborting!\n", stdout);
      }
      break;
    } else if (res == 0) {
      // Handle parse error.
      fputs("Sorry, I did not understand. Try again.\n", stdout);
      clearerr(stdin);
      for (int r = 0; r != EOF && r != '\n'; r = fgetc(stdin)) {}
    } else {
      // Handle successful input.
      acc += val;
      ++total;
    }
  }
}
