Why can't I find the EOF value in C?

I am reading the book "C Programming Language", and there is an exercise that asked me to confirm that the expression getchar() != EOF returns 1 or 0. Now the source code before I was asked to do this:

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

So I decided to change 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:

 int main() { printf("Press a key\n\n"); printf("The expression getchar() != EOF evaluates to %d\n", getchar() != EOF); } 

Could you explain to me why my method did not work?

+7
source share
6 answers

Because if c is an EOF , the while ends (or does not even start if it is already EOF for the first character entered). The condition for starting another loop iteration is that c NOT EOF .

+5
source

To display an EOF value

 #include <stdio.h> int main() { printf("EOF on my system is %d\n", EOF); return 0; } 

EOF is defined in stdio.h usually as -1

+4
source

EOF can be started using the keyboard by pressing ctrl + d on Unix and ctrl + c on Windows.

Code example:

  void main() { printf(" value of getchar() != eof is %d ",(getchar() != EOF)); printf("value of eof %d", EOF); } 

Output:

 [ root@aricent prac]# ./a.out a value of getchar() != eof is 1 value of eof -1 [ root@aricent prac]# ./a.out Press ctrl+d value of getchar() != eof is 0 value of eof -1[ root@aricent prac]# 
+3
source
 Here is my one, i went through the same problem and same answer but i finally found what every body want to say. System specification :: Ubuntu 14.04 lts Software :: gcc yes the value of EOF is -1 based on this statement printf("%i",EOF); but if your code contain like this statement while((char c=getchar)!=EOF);; and you are trying to end this loop using -1 value, it could not work. But instead of -1 you press Ctrl+D your while loop will terminate and you will get your output. 
+1
source

do it c! = EOF. Because you want to print the result of the expression, not the character.

0
source

in your program, you read the character from the input std as c = getchar ();

this way you can get the ascii value of the pressed key, which will never be equal to EOF.

since EOF is the end of the file.

it’s best to try to open any existing file and read from the file, so when it reaches End of File (EOF) it will end the while loop.

Good answer in the book:

 int main() { printf("Press a key\n\n"); printf("The expression getchar() != EOF evaluates to %d\n", getchar() != EOF); } 

try to understand the program, it will get a key that will not be equal to EOF, so it should always print "Expression getchar ()! = EOF evaluates to 0".

hope this helps .......

-2
source

All Articles