getChar()在第二次称为第二次时保持返回eof值
我很难理解 getchar()
和 eof
。
我试图运行此代码:
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
char c;
int a = 0; //no. of characters
while (1) {
c = getchar();
if (c == EOF) {
// printf("%i",c);
break;
}
putchar(c);
++a;
}
printf("%i", a);
int b;
while ((b = getchar()) != EOF) {
putchar(b);
}
printf("here"); // to check wether the code written after the loop is executed
}
我两次按CTRL-D终止了第一个循环,我发现了许多帖子,解释了其原因。但是,每当我尝试调用 getchar()
函数后,第一个循环后,即使在第一个循环中的最后一个调用中,它已经通过了最后一个调用来返回 eof
。
代码编辑器-VSCODE
OS -MACOS
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您必须将
c
定义为int
,以适应来自getchar()
的可能返回值的完整范围,即类型unsigned char 和特殊负值
eof
(通常定义为( - 1)
)。在大多数Unix系统上,当 ctrl-d 在 ctrl-d “> canonical 模式,终端缓冲的任何输入都将发送到该过程。就您而言,这会导致输入回声。如果没有此类输入待处理,则终端将零字节发送到该过程,该过程被OS解释为文件末尾。击打 ctrl-d 连续两次,或更精确地在读取请求开始时立即返回
eof
,而无需从终端请求更多用户输入。You must define
c
as anint
to accommodate for the full range of possible return values fromgetchar()
, namely all values of typeunsigned char
and the special negative valueEOF
(usually defined as(-1)
).On most unix systems, when Ctrl-D is typed in the terminal in canonical mode, whatever input has been buffered by the terminal is sent to the process. In your case, it causes the input to be echoed. If there is no such input pending, the terminal sends zero bytes to the process, which is interpreted by the OS as the end of file. Hitting Ctrl-D twice in a row, or more precisely at the beginning of a read request, does not enter an
EOF
byte, it signals the end of file to the reading process, hence any further attempt at reading from the stream will returnEOF
immediately without requesting more user input from the terminal.