2

I'm reading through the K&R book and implemented the 'copy' example:

#include <stdio.h>

int main() {
    char c;
    while ((c = getchar()) != EOF) {
        putchar(c);
    }
    return 0;
}

All normal input appears to work correctly but when an EOF (^D) is entered the program prints infinite "�" characters and I must halt the program manually.

I have tried using putchar(c); as well as printf("%c", c); to the same effect.

Does anyone know the cause of this?

2 Answers2

0

Using int c instead of char c should solve your issue

0

Since c is of type char, an int value returned from getchar will be converted to the type char before it is compared to EOF.

Since the EOF is an in-band error mechanism, it has to be an error value that can be distinguished from all valid characters that could be returned. When you assign EOF to a char you discard information.

After executing:

char c = EOF;

the statement

c == EOF

is false.

Preserve the return type of getchar by doing:

int c;

instead of:

char c;
Thomas Jager
  • 4,836
  • 2
  • 16
  • 30