Edwin Chan Edwin Chan - 2 months ago 7x
C Question

How to use fflush in c on OS/X

program source codeHow should I use

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


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')

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.