Search code examples
cgetcharfgetcgetc

Replacing getchar with fgetc or getc in while(getchar() != '\n');


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?


Solution

  • 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);