1

Rewrite the program to distinguish EOF from error for the Getchar () function. In other words, getchar () returns both during the error and at the end of the EOF file, you need to distinguish this, the input should not be via FILE STREAM and handle putchar() function errors.

#include <stdio.h>
  
int main() { 

    long nc;
    nc = 0;
    while (getchar() != EOF)
    ++nc;
    printf ("%ld\n", nc);
    
  }
Qualcomm
  • 52
  • 4

1 Answers1

0

You can check the return values of either feof() or ferror() (or both), using stdin as the FILE* argument:

#include <stdio.h>
  
int main() { 

    long nc;
    nc = 0;
    while (getchar() != EOF) ++nc;
    printf ("%ld\n", nc);
    if (feof(stdin)) printf("End-of file detected\n");
    else if (ferror(stdin)) printf("Input error detected\n");
//  Note: One or other of the above tests will be true, so you could just have:
//  else printf("Input error detected\n"); // ... in place of the second.
  }
Adrian Mole
  • 49,934
  • 160
  • 51
  • 83
  • You should always get one or the other, so `else if (...)` can probably be replaced with just `else`. – HolyBlackCat Jul 15 '20 at 11:15
  • @HolyBlackCat Yes, indeed (see edit). However, I wanted to show the use of both function calls. – Adrian Mole Jul 15 '20 at 11:18
  • Pedantic: possible for neither to be true on uncommon platforms (some old graphics processors) that employ an `unsigned char` the same size as `int`. But little need to code for that aberration. Possible to get both true if code was `getchar(); while (getchar() != EOF) ++nc;` due to input error on first and end-of-file on next. – chux - Reinstate Monica Jul 15 '20 at 15:01