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

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

问题描述

如何刷新标准输入

为什么不能在以下code段工作?

 的#include<&string.h中GT;
#包括LT&;&stdio.h中GT;
#包括LT&;&malloc.h所GT;
#包括LT&;&fcntl.h GT;诠释的main()
{
        INT I = 0,J = 0,坐下。
        精氨酸的char [256];
        字符* argq;
        argq =的malloc(sizeof的(字符)* 10);        的printf(输入行\\ n);
        我读=(0,阿根廷,sizeof的(字符)* 9);
        精氨酸[I-1] ='\\ 0';
        fflush(标准输入);        我读=(0,argq,sizeof的(字符)* 5);
        argq [I-1] ='\\ 0';        看跌期权(ARG);
        看跌期权(argq);        返回0;
}

现在,如果我给输入为11个字符,只有9应该读,但在标准输入剩下的两个字符都没有刷新,并在argq再次读取。为什么呢?

输入:
123 456 789

输出:
123 456
89

为什么我收到这89作为输出?


解决方案

我相信fflush只输出流中。

您可以尝试 fpurge 或的 __在Linux上fpurge 。需要注意的是fpurge是非标准,不便于携带。它可能不是提供给您。

的Linux fpurge手册页:通常它是要放弃输入缓冲器错误

冲厕标准输入可能会遵循以下线的东西最轻便的解决方案:

  INT℃;
而((C =的getchar())='\\ n'和;!&安培;!C = EOF);

How to flush the stdin??

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\n");
        i=read(0, arg, sizeof(char)*9);
        arg[i-1]='\0';
        fflush(stdin);

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

        puts(arg);
        puts(argq);

        return 0;
}

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?

Input: 123 456 789

Output: 123 456 89

Why am i getting this 89 as the output?

解决方案

I believe fflush is only used with output streams.

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

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()) != '\n' && c != EOF);

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

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