首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >为Getchar ()函数区分EOF和error

为Getchar ()函数区分EOF和error
EN

Stack Overflow用户
提问于 2020-07-15 11:07:08
回答 1查看 200关注 0票数 1

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

代码语言:javascript
运行
复制
#include <stdio.h>
  
int main() { 

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

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-07-15 11:14:11

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

代码语言:javascript
运行
复制
#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.
  }
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/62913496

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档