0
代码如下:如何清除C控制台应用程序中的键盘缓冲区?
#include <stdio.h>
#include <signal.h>
#include <stdlib.h>
#define SIZE 1024
char buffer[SIZE] = {0};
void timeout(int sig);
int main(void)
{
signal(SIGALRM, timeout);
alarm(3);
printf("[Input]: ");
fflush(stdout);
fgets(buffer, SIZE, stdin); // #1, enter some contents
return 0;
}
/* if #1 is not over within 3 seconds
I want to clear the keyboard buffer filled at #1, and reenter some new contents
*/
void timeout(int sig)
{
printf("\r \r[Input]: ");
fflush(stdout);
// clear the keyboard buffer pressed at #1
// ... // how to implement it?
fgets(buffer, SIZE, stdin); // #2, reenter some new contents
printf("%s", buffer); // I expect it output the contents filled at #2 only, not include that of #1
exit(0);
}
微软CSDN说退()函数可以清除键盘缓冲区,但我并没有在Linux上运行。
我看到某处C++标准库的std :: cin.igore()也可以得到相同的效果。
但是如何在C语言中实现它?
您不应该清除输入缓冲区。由于某种原因,用户可能会将数据放入其中。 –
哇!信号处理程序中禁止所有的stdio函数。不要这样做。 –