-4

program source codeHow should I use fflush in C on OS/X? When I use it, it does not clear my buffer and terminates the program straight away.

Edwin Chan
  • 33
  • 6

1 Answers1

0

Calling fflush(stdin); invokes undefined behavior. You should not use this to flush characters from the standard input buffer. Instead, you can read the characters upto the next linefeed and ignore them:

int c;
while ((c = getchar()) != EOF && c != '\n')
    continue;

You can also use scanf() for this, but it is tricky:

scanf("%*^[\n]");  // read and discard any characters different from \n
scanf("%*c");      // read and discard the next char, which, if present, is a \n

Note that you cannot combine the 2 calls above because it would fail to read a linefeed non preceded by any other characters, as the first format would fail.

chqrlie
  • 131,814
  • 10
  • 121
  • 189