Why does getchar() recognize EOF only in the beginning of a line?

后端 未结 4 1452
情深已故
情深已故 2021-01-05 12:14

This example is from the K&R book

#include


main()
{
    long nc;

    nc = 0;
    while(getchar() != EOF)
        ++nc;
    printf(\"%ld         


        
4条回答
  •  情书的邮戳
    2021-01-05 12:37

    I happened to have the same question as you. When I want to end the function getchar(), I have to enter 2 EOF or enter a plus a EOF.

    And here's an easier answer I searched about this question:

    If there is characters entering in the terminal, EOF will play the role as stopping this entering, which will arouse a new turn of entering; while, if there is no entering happening, or in another word, when the getchar() is waiting for a new enter(such as you've just finished entering or a EOF), the EOF you are about to enter now equals "end of file", which will lead the program stop executing the function getchar().

    PS: the question happens when you are using getchar(). I think this answer is easier to understand, but maybe not for you since it is translated from Chinese...

提交回复
热议问题