I wrote this code :
#include <stdio.h>
int main() {
int c;
while ((c = getchar()) != EOF)
putchar(c);
return 0;
}
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);
}