EOF和普通整数有什么区别?

发布于 2024-12-01 10:07:10 字数 528 浏览 1 评论 0原文

下面是代码

代码:

#include <stdio.h>



int main(void)
{
    int ch;

    while((ch = getchar()) != 'h')
        putchar(ch);


    return 0;
}

问题:

1.)像往常一样,我只是运行此代码,由于好奇,当程序提示输入时,我插入 ^ z(CTRL + Z) 这是 EOF(Windows 7 命令提示符) ,但我得到的只是无限循环的字符打印。

2.)从代码中,我的逻辑是,由于我向程序输入 ^z ,它只会评估逻辑 (ch = getchar()) != 'h'< /code> 和值 true1 将被返回,字符 ^z 将被打印出来。但不同的结果是yield。

below is the code

Code :

#include <stdio.h>



int main(void)
{
    int ch;

    while((ch = getchar()) != 'h')
        putchar(ch);


    return 0;
}

Question :

1.)So as usual i just run this code , due to curiosity when the program prompt for input , i insert ^z(CTRL + Z) which is EOF (Windows 7 Command Prompt) , but all i get is infinite looping of character printing.

2.)From the code , my logic is that since i input ^z to the program , it'll just evaluate the logic (ch = getchar()) != 'h' and value true or 1 will be returned and character ^z will be printed out.But instead different result is yield.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

萌逼全场 2024-12-08 10:07:11

当您按 ^Z 时,程序会注意到输入流已关闭,但您继续使用 getchar(),因此您会得到 EOF。这会无限循环,因为您无法再输入 'h' 。请注意, 'h'(不是 'A',也不是 ^M ,并且也不是 ^Z)可以停止程序,因为如果没有得到“h”,则循环

换句话说,如果您想在输入除 'h' 之外的任何其他内容时停止,则执行以下操作

do
{
    ch = getchar();
    putchar(ch);
} while (ch == 'h');

When you press ^Z, the program notices the input stream was closed, but you keep on using getchar(), so you get EOF. This loops infinitely, since you can't input 'h' anymore. Note that only 'h' (not 'A', not ^M, and also not ^Z) can stop the program, since you loop if you don't get a 'h'.

In other words, if you want to stop if anything else but 'h' is entered, then do

do
{
    ch = getchar();
    putchar(ch);
} while (ch == 'h');
梦醒时光 2024-12-08 10:07:11

EOF 通常定义为 -1(但它是特定于实现的)。当您调用 putchar(-1) 时,它将转换为 unsigned char,并变为值 255,然后输出(除非我弄错了,否则)。

EOF is typically defined as -1 (but it's implementation specific). When you call putchar(-1), it will be converted to unsigned char, and become the value 255, which is then output (ÿ unless I'm mistaken).

愚人国度 2024-12-08 10:07:11

EOF 一个具有实现定义的负值的整数。您的代码无限循环,因为只有输入“h”才能完成。但是一旦它读取到 EOF,即 != 'h',它就会进入无限循环,因为标准输入已关闭,没有任何东西可以让它返回任何其他内容。

EOF is an integer with an implementation-defined negative value. Your code loops indefinitely because only entering 'h' would make it finish. But once it reads EOF, which is != 'h', it enters an infinite loop because the standard input is closed and there is nothing that can make it return anything else.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文