1

People usually mention

while( getchar() != '\n' )

when it comes to clearing the input buffer or overflow.

fgetc or getc also work. For example:

while( fgetc(stdin) != '\n' )

and

while( getc(stdin) != '\n' )

Is there any particular reason why people always use getchar?

Is there any disadvantage to using fgetc or getc?

jwpfox
  • 5,124
  • 11
  • 45
  • 42
GabesGates
  • 13
  • 3

2 Answers2

2

People prefer getchar only in situations when they read from standard input. There is no reason why one wouldn't replace it with getc/fgetc when reading from a file is needed.

With this said, the construct is dangerous, because it can lead to an infinite loop in situations when there is no '\n' in the input stream. For example, if end-user closes the stream with Ctrl+D or Ctrl+Z, a program with a while loop like yours will never exit. You need to check for EOF in a loop that ignores input:

int ch;
while ((ch = getchar()) != '\n' && ch != EOF);
Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
0
  • If you know you're reading from stdin, use getchar.
  • If you're reading from an arbitrary file pointer, use getc.
  • If for some obscure reason you need to ensure that you're calling an actual function rather than a macro, use fgetc. (For me, those reasons are so obscure that I never call fgetc, and I recommend using getc.)
Steve Summit
  • 45,437
  • 7
  • 70
  • 103