Windows下EOF的值 [英] Value of EOF under windows

查看:57
本文介绍了Windows下EOF的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我写了这段代码:

#include <stdio.h>

int main() {
    int c;

    while ((c = getchar()) != EOF)
        putchar(c);

    return 0;
}

在Windows下,我发现必须输入ctrl + z才能停止程序,我还打印了EOF的值,它是-1.但是,当我输入-1而不是ctrl + z时,程序将继续执行,并且我想了解原因.谢谢!

Under windows, I figured out that I have to input ctrl+z so I can stop the program, I also printed the value of EOF and it's -1. However, when I enter -1 instead of ctrl+z the program continues to execute, and I want to understand why. Thank you!

推荐答案

以文本形式输入-1" 不会返回整数值 -1 ,而是两个字符,即'-'(对应于ASCII值 45 )和'1'(对应ASCII值 49 ).两者都不等于 EOF (十进制为 -1 ).

Entering "-1" as text does not return the integer value -1 but two characters, i.e. a '-' (which corresponds to ASCII value 45) and a '1' (which corresponds to ASCII value 49). Both do not compare equal to EOF (which is -1 in decimal).

根据定义,您不能输入 getchar()消耗为负值的内容,因为定义了负值来表示文件尾".

By definition, you cannot enter something that is consumed as negative value by getchar(), as negative values are defined to represent the "End-of-file".

如果要读取整数值(例如 -1 ),请使用 scanf :

If you want to read in an integral value (like -1), use scanf:

int num;
if (scanf("%d", &num)==1) { // successfully read one valid integral value?
    printf("you entered number %d:", num);
}

这篇关于Windows下EOF的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆