如何在C控制台应用程序中清除键盘缓冲区?
代码如下:如何在C控制台应用程序中清除键盘缓冲区?,c,io,C,Io,代码如下: #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(
#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);
}
#包括
#包括
#包括
#定义大小1024
字符缓冲区[大小]={0};
无效超时(int-sig);
内部主(空)
{
信号(SIGALRM,超时);
警报(3);
printf(“[输入]:”);
fflush(stdout);
fgets(buffer,SIZE,stdin);//#1,输入一些内容
返回0;
}
/*如果#1未在3秒内结束
我想清除在#1处填充的键盘缓冲区,然后重新输入一些新内容
*/
无效超时(int sig)
{
printf(“\r\r[输入]:”);
fflush(stdout);
//清除在#1按下的键盘缓冲区
//…//如何实现它?
fgets(buffer,SIZE,stdin);//#2,重新输入一些新内容
printf(“%s”,buffer);//我希望它只输出在#2处填充的内容,不包括#1的内容
出口(0);
}
微软的CSDN说rewind()函数可以清除键盘缓冲区,但我不在linux上工作。我看到C++ C++标准库的STD::CIN。IGORE()也可以得到同样的效果。
但是如何用C语言实现它呢?由于stdin是一个终端,您可以使用tcflush函数
tcflush(STDIN_FILENO, TCIFLUSH);
查看以包含正确的头文件。您也可以查看,然后停止使用报警。您不应该清除输入缓冲区。用户可能出于某种原因将数据放入其中。哇!信号处理程序中禁止所有stdio函数。不要这样做,不要在这里工作
scanf
后接tcflush
后接fgets
和fgets
获取\n
scanf留下的。