开发者

how to read anything after EOF has occured

开发者 https://www.devze.com 2023-02-13 12:36 出处:网络
I was studing the c programming book of k & r. There is this program to count no of characters in input

I was studing the c programming book of k & r. There is this program to count no of characters in input

#include<stdio.h>
main()
{
long nc;
nc=开发者_StackOverflow社区0;
while(getchar()!=EOF)
     ++nc;
printf("%ld\n",nc);
}

I was wondering how come after EOF has occured nc can be printed. Is there any way to it.


The end-of-file condition only affects stdin, not stdout. Note that there are no uses of stdin after the EOF is found, just printouts to stdout.


I think you're getting two different things mixed up. EOF is with regard to input. printf is an output function.


getchar() reads from stdin. printf() writes to stdout. They are different streams that usually map to the same physical device (console or terminal).


You should not count on a Ctrl-Z or any terminator If you were counting on that and were running on traditional *nix shells you would suspend your process rather than terminate the input (read up on JOB CONTROL, in man bash, for example)

(I know this answer comes a bit late but I see you keep mentioning Ctrl-Z in you responses to other answers)

If you are on a *nix system you can use Ctrl-D, but dont expect that to end up in your input stream (its just used as a signaling mechanism).m You can also test this with a file input which should give you more consistent results than typing, i.e.

a.out < prog.c

to count the lines in your c program

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号