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.
Asked
Active
Viewed 578 times
-4

Edwin Chan
- 33
- 6
-
4Don't tell me you fflush-ed on `stdin`.... it invokes [undefined behavior](https://en.wikipedia.org/wiki/Undefined_behavior). – Sourav Ghosh Aug 01 '16 at 11:20
-
2Please show us your code as a [mcve] (or buy us all crystal balls). – kaylum Aug 01 '16 at 11:39
1 Answers
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