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.
}
  • https://stackoverflow.com/questions/7898215/how-to-clear-input-buffer-in-c – Saaransh Garg Aug 29 '22 at 14:32
  • 1
    `tmp` is too small, it needs to be at least sized 2 to have a string with 1 char and a NUL terminator. – yano Aug 29 '22 at 14:33
  • You will lose the option to run your program with input redirection... – the busybee Aug 29 '22 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. – DevonMartin Aug 29 '22 at 14:40
  • " I require input to make a user press enter to continue. So I don't actually need to read anything." --> Enter, (aka `'\n')` is _something_. It is an input. So code needs to read that. – chux - Reinstate Monica Aug 29 '22 at 16:32
  • 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. – chux - Reinstate Monica Aug 29 '22 at 16:35
  • @chux-ReinstateMonica Appreciate the ```CLOCKS_PER_SEC``` tip, didn't catch that issue. As far as ```'\n'``` being read, I'm not understanding why that's necessary. My whole program relies on my req_input and I've never had an issue with it. I've done extensive testing trying to break it, and couldn't manage to. – DevonMartin Aug 30 '22 at 19:44

0 Answers0