打印EOF值的预期程序

时间:2013-08-28 13:51:43

标签: c for-loop scanf eof

在代码中:

#include<stdio.h>

int main()
{
    int t;
    for(;scanf("%d",&t);printf("%d",t));

}

当我将普通汉堡作为输入时,程序按预期运行。我在Windows上工作,所以当我将Cntrl + Z扫描到参数t时,我没有得到标准输出上的EOF值,即-1,而是存储在其中的前一个参数。 此外,当我按Cntrl + D程序终止时,为什么Cntrl + D导致scanf返回0?

为什么在scanf Cntrl + C上我的编译器说:“进程终止,状态为-107 ......” 我不明白为什么会这样?请帮忙。

2 个答案:

答案 0 :(得分:6)

scanf返回成功匹配的格式说明符的数量,如果在匹配(或未匹配)第一个说明符之前已达到输入结束,则返回EOF

当您按Ctrl + Z时,scanf到达输入的末尾并返回EOF(因为Ctrl + Z终止了Windows上的输入)。这不会终止您的for循环,因为EOF非零,因此会打印前一个t值(因为t未被调用更改)。请注意,t在输入结束时不会收到值EOF,因为您似乎期望:scanf返回EOF作为返回值,它不会写入进入你传递给它的指针。

当您按Ctrl + D时,它将被视为任何其他字符。由于它是非数字的,因此会导致%d说明符匹配失败,scanf返回0,从而终止循环。

答案 1 :(得分:0)

尝试此代码,如果按CTL + Z(Linux上的CTL + D),则会给出零。否则打印1

#include <stdio.h>
main()
{
        int c;

        while(c=getchar()!=EOF) //here get the character and then compares with the EOF if Not equal 1 will assign to c , if equal 0 will assign to c.
                printf("%d",c);
                printf("%d",c);//when ever we press ctl+Z(ctl+d on linux) then it will print zero remaing all cases this statement wont execute
getchar();
}