c语言 - 使用"getchar()"和"EOF"期间的无意义的输出流



我一直在尝试getchar()putchar()并一直在尝试使用EOF。下面是我一直在试验的代码片段。

#include <stdio.h>
int main(void)
{
int c;
c = getchar();
while(c != EOF)
{
putchar(c);
printf("n");
printf("%dn", EOF);
c = getchar();
}
return 0;
}

输入:-

一个

预期输出: -

//Due to putchar()

-1//Value of EOF

//Now the cursor should come in next line and wait for next character.

实时输出: -

一个

-1

-1

//Cursor waiting for next character.

我无法理解输出显示两次-1的原因。

你的代码注释说

//Now the cursor should come in next line and wait for next character.

但第二个循环不会等待。它读取已输入的换行符,这由输出中的额外空行显示。

在循环之前的第一个输入之后

c = getchar();

输入缓冲区包含与按下的键 Enter 对应的换行符'n'

所以在while循环中有输出

a

-1

由于声明

printf("%dn", EOF);

之后这个语句在循环中

c = getchar();

读取输入缓冲区中存在的换行符。所以这句话又来了

printf("%dn", EOF);

输出

-1

最新更新