うちわ 密か うちわ 密か - 8 months ago 61
C Question

Value of EOF under windows

I wrote this code :

#include <stdio.h>

int main() {
int c;

while ((c = getchar()) != EOF)
putchar(c);

return 0;
}


Under windows, I figured out that I have to input ctrl+z so I can stop the program, I also printed the value of EOF and it's -1.
However, when I enter -1 instead of ctrl+z the program continues to execute, and I want to understand why. Thank you!

Answer Source

Entering "-1" as text does not return the integer value -1 but two characters, i.e. a '-' (which corresponds to ASCII value 45) and a '1' (which corresponds to ASCII value 49). Both do not compare equal to EOF (which is -1 in decimal).

By definition, you cannot enter something that is consumed as negative value by getchar(), as negative values are defined to represent the "End-of-file".

If you want to read in an integral value (like -1), use scanf:

int num;
if (scanf("%d", &num)==1) { // successfully read one valid integral value?
    printf("you entered number %d:", num);
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download