Search code examples
ckernighan-and-ritchie

EOF adds to counter, no idea why


I have been stuck trying to understand why triggering eof using ctrl-D adds to a counter in a for loop.

Here is my code:

#include <stdio.h>
int main()
{
    double nc;
    for (nc = 0; getchar() != EOF; nc++){
       getchar();
    }
    printf("%.0f\n", nc);
    return 0;
}

My outcome is :

0
1
2
3
4
5
6
7
8

The 8 is what's given to me when I use ctrl-D after inputting 7. Is there a reason why triggering the eof causes the code to run another complete loop? I thought an empty buffer will return nothing.


Solution

  • Here is something you might miss. Take piece of your code:

    for (nc = 0; getchar() != EOF; nc++)
        getchar();
    

    There are two getchar(). Let's call them, getchar1() and getchar2(). Your input should be like this:

    0\n
    .
    .
    .
    7\n
    EOF
    

    getchar1() catch the sequence of digits and EOF. getchar2() always catch the newline ('\n'). And the count of you go through for loop body is 8 (0 to 7).

    Hope it helpful for you.