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]$ 

 

转载于:https://www.cnblogs.com/wjshan0808/p/3326337.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值