从C中的eof恢复标准输入 [英] Recover stdin from eof in C

查看:139
本文介绍了从C中的eof恢复标准输入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用下面的C代码从终端读取用户输入。如果用户输入EOF,例如通过按^ C键,关闭stdin并随后尝试从中读取,例如通过getchar()或scanf(),将导致异常。

I am using the C code below to read user input from a terminal. If the user inputs EOF, e.g. by pressing ^C, stdin is closed and subsequent attempts to read from it, e.g. via getchar() or scanf(), will cause an exception.

在C语言中我可以做些什么来恢复我的程序吗?用户不小心输入了EOF,这将被忽略,因此我可以再次从stdin中读取?

Is there anything I can do in C to "recover" my program, in the sense that if some user accidently inputs EOF, this will be ignored, so I can read from stdin again?

#include <stdio.h>

int main(void)
{
    int res_getchar=getchar();
    getchar();
    return 0;
}


推荐答案

使用 ungetc()推回一个字符可以清除流的EOF指示器。

Using ungetc() to push back a character can clear the EOF indicator for a stream.


C99§7.19 .7.11 ungetc 函数

 int ungetc(int c, FILE *stream);

成功调用 ungetc 函数清除流的文件结束指示符。读取或丢弃所有推回的字符后,流的文件位置指示符的值应与推回字符之前的值相同。 。

A successful call to the ungetc function clears the end-of-file indicator for the stream. The value of the file position indicator for the stream after reading or discarding all pushed-back characters shall be the same as it was before the characters were pushed back.

这篇关于从C中的eof恢复标准输入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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