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
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
.
EOF can be triggered through keyboard by pressing keys ctrl+d in Unix and ctrl+c in Windows.
Sample Code:
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]#
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
make it c!=EOF instead. Because you want to print the result of the expression and not the character.
in your program you are reading character from std input as c = getchar();
this way you can get ascii value of key pressed, Which will never be equal to EOF.
because EOF is End of File.
better you try to open any existing file and read from the file, so when it reached End Of File(EOF), it will quit the while loop.
well 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);
}
try to understand the program, it gets a key, which will not be equal to EOF so it should always print "The expression getchar() != EOF evaluates to 0".
hope it helps.......
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.