1

为Getchar()函数重写程序以区分EOF和错误。换句话说,getchar()在出错期间和EOF文件末尾都返回,你需要区分这一点,输入不应该是通过FILE STREAM和处理putchar()函数错误。

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

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

1 回答 1

0

您可以使用作为参数检查其中一个feof()ferror()(或两者)的返回值:stdinFILE*

#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.
  }
于 2020-07-15T11:14:11.953 回答