代码如下:
#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 说 rewind() 函数可以清除键盘缓冲区,但我在 linux 上不起作用。
我在某处看到 C++ 标准库的 std::cin.igore() 也可以获得相同的效果。
但是如何用C语言实现呢?