问题
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.
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
}
回答1:
Since you are using a linux environment, you can try using tcflush()
Link to tcflush documentation
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
}
回答2:
You basically can't; The notion of "discarding user input during a certain amount of time" doesn't really make any sense for standard out- and input, consider the fact that your input might come from a file for instance (the problem here is that 'time' isn't really a concept that exists in any way in the standard in/output routines).
You'd need a terminal API for that, and there's nothing like that in the C standard library, although there are libraries that provide capabilities like that (but you already said you didn't want to use external libraries).
回答3:
One way would be to use a thread for the countdown.
The main code starts the countdown thread, then loops to get an input.
If the input function returns before the thread has terminated, or the wrong reply was entered, ignore the input and repeat the loop.
来源:https://stackoverflow.com/questions/55474450/how-do-i-discard-user-input-delivered-during-sleep-function