在C中的EOF之后执行 [英] execute after EOF in C

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

问题描述

我正在为C编程课做作业。问题指出编写一个程序,该程序以字符流的形式读取输入,直到遇到EOF为止。我在Macbook上使用Xcode,我知道使程序遇到EOF的唯一方法是使用ctrl + D或ctrl +Z。但是它将完全退出我的程序。

I'm doing homework for my C programming class. The question states "Write a program which reads input as a stream of characters until encountering EOF". I'm using Xcode on my macbook and the only way I know to make the program encounter EOF is using ctrl + D or ctrl + Z. But it will exit my program completely.

例如,我有以下代码:

int main()
{
    int ch;
    while ((ch = getchar()) != EOF)
    {
        putchar(ch);

    }
    printf("%d",ch);
    return 0;
}

是否有代码可以执行printf(%d, ch)在循环之后(在我按键盘上的ctrl + D之后)?

Is there away for the code to execute the printf("%d",ch) after the loop (after i hit ctrl + D on my keyboard)?

推荐答案


I在Macbook上使用Xcode,我知道使程序遇到EOF的唯一方法是使用ctrl + D或ctrl +Z。但是它将完全退出我的程序。

I'm using Xcode on my macbook and the only way I know to make the program encounter EOF is using ctrl + D or ctrl + Z. But it will exit my program completely.

不,不会。如果您在Xcode调试器中运行程序,只要控制台窗格具有焦点,那么您键入的所有输入都将进入您的程序(请注意,默认情况下,stdin是行缓冲的,因此,只有在按返回键)。如果您按Control-d(而不是Control-z),则程序将退出循环并在控制台窗口中显示-1(这是您期望的,因为这是OS X中EOF的值)。

No it won't. If you run your program in the Xcode debugger, provided the console pane has the focus, all input you type will go to your program (note that, by default, stdin is line buffered, so you'll only see output when you press the return key). If you hit control-d (not control-z), you're program will exit the loop and print -1 in the console window (which is what you expect because that is the value of EOF in OS X).

这是我在Xcode调试器中运行但未更改的程序的结果(我在Xcode中键入command-r)

Here is the result when I ran your program without change in the Xcode debugger (I typed command-r in Xcode)

bgbgdfsfd

bgbgdfsfd

hgfdgf

hgfdgf

-1

bgbgdfsfd
bgbgdfsfd
hgfdgf
hgfdgf
-1

我输入了常规字体,粗体字来自您的程序。在我键入的每一行的末尾,我按回车键。在您的程序打印 hgfdgf 之后,我键入了control-D。然后,您的程序会打印出从 getchar()获得的最后一件事的值,该结果为 EOF OS XC库中的$ c> -1 。

Regular font was typed by me, bold font was from your program. At the end of each of the lines typed by me, I pressed carriage return. After your program printed hgfdgf I typed control-D. Your program then printed the value of the last thing it got from getchar() which was EOF which is -1 in the OS X C library.

编辑

如果不确定程序是否正在打印EOF,请将 printf 格式字符串更改为(for例如)

If you are unsure that your program is printing the EOF, change your printf format string to (for example)

printf("Last character is [%d]\n", ch);

然后您的程序将代替 -1 输出最后一个字符在最后一行是[-1]

Then instead of -1 your program will output Last character is [-1] on the last line.

这篇关于在C中的EOF之后执行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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