How to 刷新标准输入??
为什么它在下面的代码片段中不起作用?
#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 中再次读取。为什么?
Input: 123 456 789
Output:
123 456
89
为什么我会得到这个89
作为输出?
我相信 fflush 仅用于输出流。
你可以尝试fpurge http://www.manpagez.com/man/3/fpurge/ or __fpurge http://linux.die.net/man/3/__fpurge在 Linux 上。请注意,fpurge 是非标准且不可移植的。您可能无法使用它。
From a Linux fpurge 手册页 http://linux.die.net/man/3/fpurge:通常想要丢弃输入缓冲区是错误的。
刷新标准输入的最便携的解决方案可能是以下内容:
int c;
while ((c = getchar()) != '\n' && c != EOF);
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)