问题描述
#include <stdio.h>
#include <stdlib.h>
int main(void) {
char text[256];
while (1) {
puts("Text?");
fgets(text,sizeof(text),stdin);
fflush(stdout); // should you flush everytime?
}
return 0;
}
例如,如果要创建用户输入并在不中断的while循环中打印,是否应该冲洗?还需要冲洗标准输入吗?
如果您也愿意使用stderr,在这种情况下是否还需要冲洗stderr?
解决方法
仅当缓冲区中有待处理的字节时,即text
中没有换行符时,才需要刷新。无论如何,您应该刷新的是stdin
(而不是stdout
):
fgets(text,sizeof(text),stdin);
// fflush(stdout); // should you flush everytime? --> NOPS
if (strchr(text,'\n') == NULL)
{
int c;
// Flush stdin
while (((c = fgetc(stdin)) != '\n') && (c != EOF));
}