ceofgetcharputchar

Distinguish EOF from error for the Getchar () function


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);
    
  }

Solution

  • 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.
      }