I have a program that prints, has a time delay, prints more, and then requires user input before proceeding. I want to ensure that if a user inputs anything before the delay is finished, it will clear that out and still require input before proceeding.
In these instances in my program, I'm just requiring "Press enter to continue" and at other instances, I receive input and use it appropriately. Everything works as intended, except that early input during a delay will proceed a user through req_input.
void delay(float time_in_s) {
int seconds = 1000000 * time_in_s;
clock_t start_time = clock();
while (clock() < start_time + seconds);
}
void clearstdin(char *string) {
if (!strchr(string, '\n')) {
while (fgetc(stdin) != '\n');
}
}
void req_input() {
char tmp[1];
fgets(tmp, sizeof(tmp), stdin);
clearstdin(tmp);
}
int main(void) {
printf("Hello world\n");
delay(2);
printf("Press enter to end program.\n");
req_input();
printf("Ending program only after input AFTER delay.\n"); // Should not trigger from input received during delay.
}