我写了这个C程序:
#include <stdio.h>
main()
{
int numspaces, numtabs, numnl, c;
while ((c = getchar()) != EOF){
if (c == ' ') ++numspaces;
if (c == '\t') ++numtabs;
if (c == '\n') ++ numnl;
}
printf("Spaces:\t\t%d\nTabs:\t\t%d\nNew lines:\t\t%d\n", numspaces, numtabs, numnl);
}
I think this while loop must finish when I press Ctrl+D and "return". It does if Ctrl+D is the first thing I type in a line. But if I start a line with other character (letter, space, tab) and then Ctrl+D and then "return" - the loop continues.
我在 Mac OS X 终端中测试了这个,我看到它回显^D
并且它仍然继续循环。我在这里缺少什么?
CTRL-D or more precisely the character set to the VEOF
entry of the c_cc
field of a termios control structure (stty
is the easiest way to query and modify those settings from the command line) is to be interpreted as (quote from the Single Unix Specification V4):
输入上的特殊字符,如果设置了 ICANON 标志,则可以识别该字符。当接收到时,所有等待读取的字节立即传递给进程,而不等待 ,并且 EOF 被丢弃。因此,如果没有字节等待(即 EOF 发生在行的开头),则 read() 应返回字节计数为零,表示文件结束指示。如果设置了 ICANON,则处理时 EOF 字符将被丢弃。
Thus to send a EOF indication from a terminal you hit CTRL-D once when there is no bytes waiting to be returned (typically at the start of a line), and twice when there are some.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)