如何丢弃睡眠功能期间传递的用户输入? [英] How do I discard user input delivered during sleep function?
问题描述
我正在尝试使用终端创建游戏.我问播放器是否准备好,然后用下面的代码倒数.问题在于,用户所做的所有输入都会添加到程序进行的下一个输入查询中.我正在寻找一种方法来丢弃先前的输入或在此功能期间完全阻止其输入.
I'm trying to create a game using the terminal. I ask if the player is ready and then make a countdown with the code down below. The problem is that all input the user makes is added to the next input query the program makes. I'm looking for a way to discard the previous input or block it entirely during this function.
我可以进行getchar循环,但是倒计时(按Enter键)后,我不需要用户输入.
I could do a getchar loop, but that would need user input after the countdown (pressing enter) which I don't want.
void countdown(void){
printf("5\n");
sleep(1);
printf("4\n");
sleep(1);
printf("3\n");
sleep(1);
printf("2\n");
sleep(1);
printf("1\n");
sleep(1);
clearScreen(0); //clears terminal
}
推荐答案
由于您使用的是Linux环境,因此可以尝试使用 tcflush()
Since you are using a linux environment, you can try using tcflush()
这是使用tcflush修改后的代码示例.您可以取消注释底部,并看到从倒数计时器缓冲区中清除了倒计时期间输入的所有内容.
Here is a modified example of your code using tcflush. You can uncomment the bottom portion and see that everything entered during the countdown is cleared from the stdio buffer.
#include <termios.h>
#include <stdio.h>
#include <unistd.h>
void main(){
char str[100];
printf("5\n");
sleep(1);
printf("4\n");
sleep(1);
printf("3\n");
sleep(1);
printf("2\n");
sleep(1);
printf("1\n");
sleep(1);
// arguments for tcflush:
// 0 is for stdin
// TCIFLUSH is to flush data received but not read
tcflush(0,TCIFLUSH);
// prove it works by uncommenting this code
// printf("fgets is waiting");
// fgets(str, sizeof(str), stdin);
// printf("%s", str);
// clearScreen(0); //clears terminal
}
这篇关于如何丢弃睡眠功能期间传递的用户输入?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!