如何刷新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;
}
Run Code Online (Sandbox Code Playgroud)
现在,如果我将输入作为11个字符,则只应读取9个,但是stdin中剩余的两个字符不会被刷新并在argq中再次读取.为什么?
输入:123 456 789
产出:123 456 89
为什么我将这89作为输出?
jsc*_*ier 35
我相信fflush仅用于输出流.
您可以在Linux上尝试fpurge或__fpurge.请注意,fpurge是非标准的,不可移植.它可能无法使用.
从Linux fpurge手册页:通常想要丢弃输入缓冲区是错误的.
用于刷新stdin的最便携式解决方案可能与以下内容类似:
int c;
while ((c = getchar()) != '\n' && c != EOF);
Run Code Online (Sandbox Code Playgroud)
小智 11
int c;
while((c = getchar()) != '\n' && c != EOF);
Run Code Online (Sandbox Code Playgroud)
我是如何清除输入缓冲区的.