这个例子来自K&R书
#include<stdio.h>
main()
{
long nc;
nc = 0;
while(getchar() != EOF)
++nc;
printf("%ld\n", nc);
}
Run Code Online (Sandbox Code Playgroud)

你能解释一下为什么它会这样运作吗?谢谢.
^ Z ^ Z也不起作用(除非它在一行的开头)

传统的 UNIX 对 tty 字符的解释是在读取熟 tty 行缓冲区内缓冲的任何内容后EOF阻塞返回。read在新行的开头,这意味着read返回 0(读取零字节),顺便说一句,0 大小read是检测普通文件的文件结束条件的方式。
这就是为什么行中间的第一个 EOF只是强制行的开头为read,而不是使 C 运行时库检测到文件结尾。一行中的两个 字符会产生 0 大小的读取,因为第二个字符强制应用程序使用空缓冲区。EOFread
$ cat
foo[press ^D]foo <=== after ^D, input printed back before EOL, despite cooked mode. No EOF detected
foo[press ^D]foo[press ^D] <=== after first ^D, input printed back, and on second ^D, cat detects EOF
$ cat
Some first line<CR> <=== input
Some first line <=== the line is read and printed
[press ^D] <=== at line start, ^D forces 0-sized read to happen, cat detects EOF
Run Code Online (Sandbox Code Playgroud)
我假设您的 C 运行时库模仿上述语义(在 Windows 上没有调用^Z级别的特殊处理kernel32,更不用说系统调用了)。^Z^Z这就是为什么即使在输入行的中间它也可能检测到 EOF 。