c-区分Getchar()函数的EOF和错误



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

#include <stdio.h>

int main() { 
long nc;
nc = 0;
while (getchar() != EOF)
++nc;
printf ("%ldn", nc);

}

您可以使用stdin作为FILE*参数来检查feof()ferror()(或两者(的返回值:

#include <stdio.h>

int main() { 
long nc;
nc = 0;
while (getchar() != EOF) ++nc;
printf ("%ldn", nc);
if (feof(stdin)) printf("End-of file detectedn");
else if (ferror(stdin)) printf("Input error detectedn");
//  Note: One or other of the above tests will be true, so you could just have:
//  else printf("Input error detectedn"); // ... in place of the second.
}

最新更新