ç|如何检查我的输入缓冲区(stdin)是否为空?

时间:2016-04-05 13:41:06

标签: c input buffer stdin

我想知道如何检查我的输入缓冲区(可能是它的名为stdin)是否为空。 如果缓冲区为空,我不希望程序停止,并且我不希望输入必须以' \ n'结束,因此仅使用scanf是不够的。

我尝试在谷歌和这个网站上搜索但没有答案就够了。 我试过像这样使用feof(stdin):

int main()
{
char c,x;
int num;
scanf("%c",&c);
scanf("%c",&x);
num=feof(stdin);
printf("%d",num);
}

但无论输入如何,它所做的只是打印0。在第二次scanf之后添加fflush(stdin)得到相同的结果。 其他答案建议使用选择和民意调查,但我找不到这些功能的任何解释。 其他一些论坛告诉我使用getchar(),但我认为他们误解了我的问题。

在谷歌搜索上我尝试过:C如何检查输入缓冲区为空,C stdin为空,c"输入缓冲区"检查空。 这是一个普遍的问题,它不适用于特定的代码,所以我无需为什么需要它。

**如果您建议我使用select / poll,您能否添加一些关于如何使用它们的说明?

4 个答案:

答案 0 :(得分:1)

以下是解决此问题的代码:

fseek (stdin, 0, SEEK_END);
num = ftell (stdin);

fseek会将指针放在stdin输入缓冲区的末尾。 ftell将返回文件大小。

答案 1 :(得分:0)

如果你不想阻止一个空的 stdin ,你应该能够 fcntl 将它强加到 O_NONBLOCK 并像对待任何一样对待它其他非阻塞I / O.此时,对 fgetc 之类的调用应立即返回,或者使用值,或者如果流为空则返回 EAGAIN

答案 2 :(得分:0)

class JavaAapplication1

试试这个,添加int ch = getc(stdin); if (ch == EOF) puts("stdin is empty"); else ungetc(ch, stdin); 以消除副作用。

答案 3 :(得分:0)

您可以使用select()来处理阻止问题,并且手册页select(2)有一个很好的示例来轮询stdin。这仍然没有解决需要行分隔符('\n')的问题。这实际上是由于终端处理输入的方式。

在Linux上,你可以使用termios,

#include <stdio.h>
#include <unistd.h>
#include <termios.h>

// immediate mode getchar().
static int getch_lower_(int block)
{
    struct termios tc = {};
    int status;
    char rdbuf;
    // retrieve initial settings.
    if (tcgetattr(STDIN_FILENO, &tc) < 0)
        perror("tcgetattr()");
    // non-canonical mode; no echo.
    tc.c_lflag &= ~(ICANON | ECHO);
    tc.c_cc[VMIN] = block ? 1 : 0; // bytes until read unblocks.
    tc.c_cc[VTIME] = 0; // timeout.
    if (tcsetattr(STDIN_FILENO, TCSANOW, &tc) < 0)
        perror("tcsetattr()");
    // read char.
    if ((status = read(STDIN_FILENO, &rdbuf, 1)) < 0)
        perror("read()");
    // restore initial settings.
    tc.c_lflag |= (ICANON | ECHO);
    if (tcsetattr(STDIN_FILENO, TCSADRAIN, &tc) < 0)
        perror("tcsetattr()");
    return (status > 0) ? rdbuf : EOF;
}

int getch(void)
{
    return getch_lower_(1);
}

// return EOF if no input available.
int getch_noblock(void)
{
    return getch_lower_(0);
}
相关问题