【问题标题】:Distinguish EOF from error for the Getchar () function [duplicate]将 EOF 与 Getchar () 函数的错误区分开来[重复]
【发布时间】:2020-07-15 11:07:08
【问题描述】:

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

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

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

【问题讨论】:

  • EOF 返回后检查feofferror
  • 但是 feof 和 ferror 不只是针对 FILE STREAM 吗?
  • 使用stdin 代替文件。
  • @PP 虽然我并没有真正质疑您的重复重复,但在 this 问题中还有一个额外的问题是必须使用stdin 作为@987654327 @ 参数,这在任何一个欺骗目标中都不明显。

标签: c eof getchar putchar


【解决方案1】:

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

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

【讨论】:

  • 你应该总是选择其中一个,所以else if (...) 可能只替换为else
  • @HolyBlackCat 是的,确实(见编辑)。但是,我想展示这两个函数调用的用法。
  • 迂腐:在使用与int 相同大小的unsigned char 的不常见平台(一些旧图形处理器)上,这两种情况都不成立。但几乎不需要为这种异常编码。如果代码为 getchar(); while (getchar() != EOF) ++nc; 由于第一个输入错误和下一个文件结束,则可能都为真。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-10-12
  • 2017-05-15
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多