fork download
  1. #include <errno.h>
  2. #include <stdio.h>
  3.  
  4. int main() {
  5. int total = 0;
  6. double acc = 0, val;
  7.  
  8. for (;;) {
  9. fputs("Value: ", stdout);
  10. fflush(stdout);
  11.  
  12. errno = 0;
  13. int res = fscanf(stdin, "%lf", &val);
  14.  
  15. if (res == EOF) {
  16. // Handle successful end of input or read error.
  17. if (errno == 0) {
  18. fprintf(stdout, "Done! You entered %d values averaging %f.\n", total, acc / total);
  19. } else {
  20. fputs("There was an error, aborting!\n", stdout);
  21. }
  22. break;
  23. } else if (res == 0) {
  24. // Handle parse error.
  25. fputs("Sorry, I did not understand. Try again.\n", stdout);
  26. clearerr(stdin);
  27. for (int r = 0; r != EOF && r != '\n'; r = fgetc(stdin)) {}
  28. } else {
  29. // Handle successful input.
  30. acc += val;
  31. ++total;
  32. }
  33. }
  34. }
  35.  
Success #stdin #stdout 0s 2160KB
stdin
5
foo
10
15
stdout
Value: Value: Sorry, I did not understand. Try again.
Value: Value: Value: Done! You entered 3 values averaging 10.000000.