Reputation: 51
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=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.
Upvotes: 0
Views: 394
Reputation: 6001
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
Upvotes: 0
Reputation: 22912
getchar() reads from stdin. printf() writes to stdout. They are different streams that usually map to the same physical device (console or terminal).
Upvotes: 0
Reputation: 17307
I think you're getting two different things mixed up. EOF is with regard to input. printf is an output function.
Upvotes: 0
Reputation: 30969
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
.
Upvotes: 2