2013-04-16 238 views
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语言中实现它?

+0

您不应该清除输入缓冲区。由于某种原因,用户可能会将数据放入其中。 –

+0

哇!信号处理程序中禁止所有的stdio函数。不要这样做。 –

回答

0

由于stdin是一个终端,您可以使用tcflush功能。

tcflush(STDIN_FILENO, TCIFLUSH); 

看那man page以包括正确的头文件。您也可以查看select man page,并停止使用警报。

+0

不在这里工作。 'scanf'后面跟着'tcflush',接着'fgets'和'fgets'得到'scanf'左边的'\ n'。 –