jiin2 jiin2 - 1 year ago 143
C Question

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.

also work. For example:

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


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

Is there any particular reason why people always use

Is there any disadvantage to using

Answer Source

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);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download