重写程序,将EOF与Getchar ()函数的错误区分开来。换句话说,getchar ()在错误期间和EOF文件末尾都返回,您需要区分这一点,输入不应该通过文件流和处理putchar()函数错误。
#include <stdio.h>
int main() {
long nc;
nc = 0;
while (getchar() != EOF)
++nc;
printf ("%ld\n", nc);
}发布于 2020-07-15 11:14:11
您可以检查feof()或ferror() (或两者都)的返回值,使用stdin作为FILE*参数:
#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.
}https://stackoverflow.com/questions/62913496
复制相似问题