How do you get to see the last print? In other words what to put in for EOF? I checked the definitions and it says EOF is -1.
And if you enter Ctrl-D you won't see anything.
#include <stdio.h>
int main() {
int c;
while((c = getchar() != EOF)) {
printf("%d\n", c);
}
printf("%d - at EOF\n", c);
}
Couple of typos:
in place of:
Also getchar() treats a return key as a valid input, so you need to buffer it too.EOF is a marker to indicate end of input. Generally it is an int with all bits set.
prints:
for input:
I think this is right way to check value of EOF. And I checked the output.
For INPUT: abc and Enter I got OUTPUT: 97 98 99 10. ( the ASCII values)
For INPUT Ctrl-D I got OUTPUT: -1 - at EOF. So I think -1 is the value for EOF.
Try other inputs instead of Ctrl-D, like Ctrl-Z. I think it varies from compiler to compiler.
EOF means end of file. It's a sign that the end of a file is reached, and that there will be no data anymore.
Edit:
I stand corrected. In this case it's not an end of file. As mentioned, it is passed when CTRL+d (linux) or CTRL+z (windows) is passed.
modified the above code to give more clarity on EOF, Press Ctrl+d and putchar is used to print the char avoid using printf within while loop.
The value of EOF is a negative integer to distinguish it from "char" values that are in the range 0 to 255. It is typically -1, but it could be any other negative number ... according to the POSIX specs, so you should not assume it is -1.
The ^D character is what you type at a console stream on UNIX/Linux to tell it to logically end an input stream. But in other contexts (like when you are reading from a file) it is just another data character. Either way, the ^D character (meaning end of input) never makes it to application code.
As @Bastien says, EOF is also returned if
getchar()
fails. Strictly speaking, you should callferror
orfeof
to see whether the EOF represents an error or an end of stream. But in most cases your application will do the same thing in either case.You should change your parenthesis to
Because the "=" operator has a lower precedence than the "!=" operator. Then you will get the expected results. Your expression is equal to
You are getting the two 1's as output, because you are making the comparison "c!=EOF". This will always become one for the character you entered and then the "\n" that follows by hitting return. Except for the last comparison where c really is EOF it will give you a 0.
EDIT about EOF: EOF is typically -1, but this is not guaranteed by the standard. The standard only defines about EOF in section 7.19.1:
It is reasonable to assume that EOF equals -1, but when using EOF you should not test against the specific value, but rather use the macro.