我无法刷新标准输入 [英] I am not able to flush stdin

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

问题描述

如何刷新标准输入??

为什么在下面的代码片段中不起作用?

Why is it not working in the following code snippet?

#include <string.h>
#include <stdio.h>
#include <malloc.h>
#include <fcntl.h>

int main()
{
        int i=0,j=0, sat;
        char arg[256];
        char * argq;
        argq = malloc(sizeof(char)*10);

        printf("Input the line
");
        i=read(0, arg, sizeof(char)*9);
        arg[i-1]='';
        fflush(stdin);

        i=read(0, argq, sizeof(char)*5);
        argq[i-1]='';

        puts(arg);
        puts(argq);

        return 0;
}

现在,如果我将输入设为 11 个字符,则只应读取 9 个字符,但不会刷新标准输入中的其余两个字符并在 argq 中再次读取.为什么?

Now if i give the input as 11 characters, only 9 should be read but the remaining two characters in the stdin are not flushed and read again in the argq. Why?

输入:123 456 789

Input: 123 456 789

输出:123 45689

Output: 123 456 89

为什么我得到这个 89 作为输出?

Why am i getting this 89 as the output?

推荐答案

我相信 fflush 只用于输出流.

I believe fflush is only used with output streams.

您可以尝试 fpurge__fpurge 在 Linux 上.请注意, fpurge 是非标准的且不可移植.您可能无法使用它.

You might try fpurge or __fpurge on Linux. Note that fpurge is nonstandard and not portable. It may not be available to you.

来自 Linux fpurge 手册页:通常想要丢弃是错误的输入缓冲区.

From a Linux fpurge man page: Usually it is a mistake to want to discard input buffers.

刷新标准输入最便携的解决方案可能是以下几行:

The most portable solution for flushing stdin would probably be something along the lines of the following:

int c;
while ((c = getchar()) != '
' && c != EOF);

这篇关于我无法刷新标准输入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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