I'm reading the book "The C Programming Language" and there is an exercise that asked to verify that the expression getchar() != EOF
is returning 1 or 0. Now the original code before I was asked to do that was:
int main()
{
int c;
c = getchar();
while (c != EOF)
{
putchar(c);
c = getchar();
}
}
So I thought changing it to:
int main()
{
int c;
c = getchar();
while (c != EOF)
{
printf("the value of EOF is: %d", c);
printf(", and the char you typed was: ");
putchar(c);
c = getchar();
}
}
And the answer in the book is:
int main()
{
printf("Press a key\n\n");
printf("The expression getchar() != EOF evaluates to %d\n", getchar() != EOF);
}
Could you please explain to me why my way didn't work?
The EOF in C/Linux is control^d on your keyboard; that is, you hold down the control key and hit d. The ascii value for EOF (CTRL-D) is 0x05 as shown in this ascii table . Typically a text file will have text and a bunch of whitespaces (e.g., blanks, tabs, spaces, newline characters) and terminate with an EOF.
1. Since EOF is an integer, we can print it with %d format in the printf. 2. EOF value is printed as -1.
EOF is a macro which expands to an integer constant expression with type int and an implementation dependent negative value but is very commonly -1. '\0' is a char with value 0 in C++ and an int with the value 0 in C.
Because if c
is EOF
, the while
loop terminates (or won't even start, if it is already EOF
on the first character typed). The condition for running another iteration of the loop is that c
is NOT EOF
.
To display the value of EOF
#include <stdio.h>
int main()
{
printf("EOF on my system is %d\n", EOF);
return 0;
}
EOF is defined in stdio.h normally as -1
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With