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

后端 未结 4 1410
情深已故
情深已故 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:44

    EOF indicates "end of file". A newline (which is what happens when you press enter) isn't the end of a file, it's the end of a line, so a newline doesn't terminate this loop.

    Depending on the operating system, EOF character will only work if it's the first character on a line, i.e. the first character after an Enter. Since console input is often line-oriented, the system may also not recognize the EOF character until after you've followed it up with an Enter.

提交回复
热议问题