如何检查是否标准输入为空,用C [英] How to check if stdin is empty in C

查看:389
本文介绍了如何检查是否标准输入为空,用C的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我(重新)学习C语言编程,所以下面的问题是为了理解起见。
使用scanf()的我学会了(或者发现了我自己,它并没有真正需要很长时间,到了这个地步)的冲洗标准输入是一件好事。我还发现了(在您的帮助)的fflush(标准输入)是不是做的,例如一个标准的东西不能与海湾合作委员会的工作。
我提出用下面的code代码段用于冲洗标准输入。正是在这里(感谢)提供。它工作正常,如果标准输入不为空。然而,如果标准输入为空,这是行不通的。在我的冲洗功能的龟etc()只是等待并阻止该程序。而事实上,所有其他标准输入读取功能,据我所知,到目前为止(scanf()的,龟etc(),获得()与fgets(),getchar函数())都显示相同的行为。所以,我的冲洗功能实际上是一种有条件的冲洗:如果缓冲区不为空,它仅仅刷新。如果是空的冲洗块的程序,并等待输入到标准输入。这不是我想要的。所以,我需要的是一个方法来检查,如果标准输入是空的。如果是我继续下去。如果不是我跑我的冲洗功能。

所以,我在找的是检查标准输入是空的一个C标准的方式。

非常感谢您的帮助!

 无效flush_line(FILE *);
/ *功能,因为*刷新标准输入在C标准的方式/
/ * fflush(标准输入)已未定义行为。 * /
/ * S。 http://stackoverflow.com/questions/20081062/fflushstdin-does-not-work-compiled-with-gcc-in-cygwin-but-does-compiled-with-v * /
无效flush_line(FILE * FIN)
{
    INT CH;
    做
    {
        CH =龟etc(翅);    }而(CH ='\\ n'和;!&安培; CH = EOF!);}


解决方案

您可以使用select或poll检查文件描述符是否可读。但是,是不是在ANSI C.

I am (re-)learning C-programming, so the following question is for the sake of understanding. Using scanf() I learned (or found out myself, it does not really take long to come to this point) that flushing stdin is a good thing. I further found out (with your help) that fflush(stdin) is not a standard thing to do and e.g. does not work with gcc. I moved on to use the code snippet below for flushing stdin. It was provided here (thanks). It works fine, if stdin is not empty. Yet, if stdin is empty it does not work. The fgetc() in my flushing function just waits and blocks the program. And in fact all other stdin-reading functions that I know of so far (scanf(), fgetc(), gets(), fgets(), getchar()) all show the same behaviour. So my flushing function is actually a conditional flushing: it only flushes if the buffer is not empty. If it is empty the flushing blocks the program and waits for an input to stdin. This is not what I want. So, what I need is a way to check if stdin is empty. If it is I continue. If it isn't I run my flushing function.

So, what I am looking for is a C standard way to check if stdin is empty.

Thanks a lot for any help!

void flush_line(FILE *);


/* function to flush stdin in a C standard way since*/
/* fflush(stdin) has undefined behaviour. */
/* s. http://stackoverflow.com/questions/20081062/fflushstdin-does-not-work-compiled-with-gcc-in-cygwin-but-does-compiled-with-v */
void flush_line(FILE *fin)
{
    int ch;
    do
    {
        ch = fgetc(fin);

    } while (ch != '\n' && ch != EOF);

}

解决方案

You can use select or poll to check whether a file descriptor is readable. But is not in ANSI C.

这篇关于如何检查是否标准输入为空,用C的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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