1

What can be the best way to flush the stdin in a .C program in VC++ along with getchar()?

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

looks very odd to me.

fflush();

and

scanf ( "%*[^\n]" );
getchar();

is not working in VC++ in case of a .C program.

Charles
  • 50,943
  • 13
  • 104
  • 142
user366312
  • 16,949
  • 65
  • 235
  • 452
  • The first method is the correct way,Why do you don't want to use it? – Alok Save Nov 30 '11 at 15:09
  • I am searching for a way that is built-into the compiler's standard library. – user366312 Nov 30 '11 at 15:24
  • 1
    There is no built-in way,In C the input is buffered, which means that when any keys are hit those are not sent to your program directly but the OS holds it backs(buffers) and sends the input to your program,this may happen at discretion of the OS.So there is no standard way of clearing an input stream.Your first example is a reasonably good way,but that may fail sometimes as well.As far as `fflush()` goes it is unsafe and you should not use it at all. – Alok Save Nov 30 '11 at 15:34
  • `fflush` is not what you want, it's for use with output streams ("make sure the whole buffer is actually written"). – Kos Nov 30 '11 at 15:48
  • @Als: `fflush()` is perfectly safe for output streams; it's undefined for input streams. (Well, it's "perfectly safe' in the sense that it can cause an error condition, but its behavior is defined.) – Keith Thompson Nov 30 '11 at 17:26
  • @KeithThompson: It is,The OP means input stream in this context, which would result in Undefined Behavior. – Alok Save Nov 30 '11 at 17:30
  • @Als: Understood. My point is that your comment, "... and you should not use it at all", could easily imply that you should *never* use it. I'm sure that wasn't your intent, but I wanted to clarify it for other readers. – Keith Thompson Nov 30 '11 at 17:39
  • @KeithThompson: Thanks for clarifying,I am sure it will help others.Possibly,I should have been more explicit. – Alok Save Nov 30 '11 at 17:46

1 Answers1

0

If you just want to detect a key being hit (and read it's value) - then that is an operating system feature. 'C' has no knowledge of keyboards (or any other hardware)

On windows use _kbhit() see What is the INKEY$ equivalent in C programming language

Community
  • 1
  • 1
Martin Beckett
  • 94,801
  • 28
  • 188
  • 263