加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

如果EOF符合第一个字符,为什么会被识别?

发布时间:2020-12-16 09:48:51 所属栏目:百科 来源:网络整理
导读:我写了这个C程序: #include stdio.hmain(){ int numspaces,numtabs,numnl,c; while ((c = getchar()) != EOF){ if (c == ' ') ++numspaces; if (c == 't') ++numtabs; if (c == 'n') ++ numnl; } printf("Spaces:tt%dnTabs:tt%dnNew lines:tt%dn
我写了这个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:tt%dnTabs:tt%dnNew lines:tt%dn",numspaces,numnl);
}

我认为当我按Ctrl D并“返回”时,while循环必须完成.如果Ctrl D是我在一行中输入的第一件事,它会这样做.但是如果我用其他字符(字母,空格,制表符)开始一行,然后按Ctrl D然后“返回” – 循环继续.

我在Mac OS X终端测试这个,我看到它回显^ D并且它仍然继续循环.我在这里错过了什么?

解决方法

CTRL-D或者更准确地说是设置为termios控制结构的c_cc字段的VEOF条目的字符(stty是从命令行查询和修改这些设置的最简单方法)将被解释为(引自Single Unix)规范V4):

Special character on input,which is recognized if the ICANON flag is set. When received,all the bytes waiting to be read are immediately passed to the process without waiting for a,and the EOF is discarded. Thus,if there are no bytes waiting (that is,the EOF occurred at the beginning of a line),a byte count of zero shall be returned from the read(),representing an end-of-file indication. If ICANON is set,the EOF character shall be discarded when processed.

因此,当没有等待返回的字节(通常在一行的开头)时,从终端发送一个EOF指示,你就按CTRL-D一次,当有一些字节时,你会按两次.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读