2

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. } 
7
  • stackoverflow.com/questions/7898215/… Commented Aug 29, 2022 at 14:32
  • 1
    <O/T> tmp is too small, it needs to be at least sized 2 to have a string with 1 char and a NUL terminator. Commented Aug 29, 2022 at 14:33
  • You will lose the option to run your program with input redirection... Commented Aug 29, 2022 at 14:33
  • I don't require input to get input, I require input to make a user press enter to continue. So I don't actually need to read anything. My program works as intended, except for my described issue of early input continuing a user through req_input. Commented Aug 29, 2022 at 14:40
  • 1
    Code assume clock() is returning microseconds. Code will wait a long time if CLOCKS_PER_SEC == 1000 for example. clock_t seconds = CLOCKS_PER_SEC * time_in_s; makes more sense. Commented Aug 29, 2022 at 16:35

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.