• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
wjshan0808

Learn from yesterday, Live for today, For a better tomorrow.
 ————wjshan0808

博客园    首页    新随笔    联系   管理    订阅  订阅

C program Language 'EOF' and 'getchar()'

#include <stdio.h>
void main()
{
    int c;
    c=getchar();
    while(c!=EOF)
    {
            putchar(c);
            c=getchar();
    }
}

getchar() returns a distinctive value when there is no more input, a value that cannot be confused with any real character. This value is called
EOF, for ``end of file''.

Q: The type char is specifically meant for storing such character data, but any integer type can be used.
We used int for a subtle but important reason.

A: We must declare c to be a type big enough to hold any value that getchar returns. We
can't use char since c must be big enough to hold EOF in addition to any possible char. Therefore we use int.

EOF is an integer defined in <stdio.h>, but the specific numeric value doesn't matter as long as it is not the same as
any char value. By using the symbolic constant, we are assured that nothing in the program depends on the
specific numeric value.

 

The next program counts characters; it is similar to the upper case:

#include <stdio.h>
void main()
{
    int nc;
    nc=0;
    while(getchar()!=EOF)
      ++nc;
    printf("\nCharacter Counting is: %1d\n",nc);
}
[15:10:28@wjshan0808 ~/Documents/C Program]$ gcc CharactersCount.c
[15:17:38@wjshan0808 ~/Documents/C Program]$ ./a.out
asdf      //Ctrl+D
Character Counting is: 4
[15:17:44@wjshan0808 ~/Documents/C Program]$ ./a.out
asdf      
        //Ctrl+D
Character Counting is: 5
[15:17:52@wjshan0808 ~/Documents/C Program]$ 

 


posted @ 2013-09-17 15:20  wjshan0808  阅读(365)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3