我无法冲洗stdin

我无法冲洗stdin

如何刷新stdin?

为什么它不能在以下代码片段中工作?

#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;}

现在,如果我将输入作为11个字符,则只应读取9个,但是stdin中剩余的两个字符不会被刷新并在argq中再次读取。为什么?

输入:123 456 789

产出:123 456 89

为什么我将这89作为输出?


慕码人8056858
浏览 720回答 3
3回答

猛跑小猪

我相信fflush仅用于输出流。您可以在Linux上尝试fpurge或__fpurge。请注意,fpurge是非标准的,不可移植。它可能无法使用。从Linux fpurge手册页:通常想要丢弃输入缓冲区是错误的。用于刷新stdin的最便携式解决方案可能与以下内容类似:int&nbsp;c;while&nbsp;((c&nbsp;=&nbsp;getchar())&nbsp;!=&nbsp;'\n'&nbsp;&&&nbsp;c&nbsp;!=&nbsp;EOF);

饮歌长啸

从comp.lang.c FAQ中,请参阅:如何刷新挂起的输入,以便在下一个提示符下不读取用户的预先输入?fflush(stdin)会工作吗?如果fflush不起作用,我可以使用什么来刷新输入?

慕姐8265434

如何刷新stdin?刷新输入流正在调用未定义的行为。不要试试。您只能刷新输出流。
打开App,查看更多内容
随时随地看视频慕课网APP