0

Code is as follows:

#include <stdio.h>
#include <signal.h>
#include <stdlib.h>

#define SIZE 1024
char buffer[SIZE] = {0};

void timeout(int sig);

int main(void)
{
    signal(SIGALRM, timeout);
    alarm(3);

    printf("[Input]: ");
    fflush(stdout);

    fgets(buffer, SIZE, stdin); // #1, enter some contents

    return 0;
}

/* if #1 is not over within 3 seconds
   I want to clear the keyboard buffer filled at #1, and reenter some new contents
*/
void timeout(int sig)
{
    printf("\r                       \r[Input]: ");
    fflush(stdout);

    // clear the keyboard buffer pressed at #1
    // ... // how to implement it?

    fgets(buffer, SIZE, stdin); // #2, reenter some new contents
    printf("%s", buffer); // I expect it output the contents filled at #2 only, not include that of #1

    exit(0);
}

Microsoft's CSDN says rewind() function can clear the keyboard buffer, but I doesn't work on linux.
I saw somewhere that C++ standard library's std::cin.igore() can also get the same effect.
But how to implement it in C language?

ZhangXiongpang
  • 280
  • 2
  • 7

1 Answers1

0

Since stdin is a terminal, you can use the tcflush function.

tcflush(STDIN_FILENO, TCIFLUSH);

Look at the man page to include the correct header files. You can also look at the select man page, and stop using alarm.

shodanex
  • 14,975
  • 11
  • 57
  • 91
  • Not working here. `scanf` followed by `tcflush` followed by `fgets` and `fgets` gets the `\n` left by the `scanf`. – DrBeco Oct 22 '15 at 22:28