问题
I wrote this code :
#include <stdio.h>
int main() {
int c;
while ((c = getchar()) != EOF)
putchar(c);
return 0;
}
Under windows, I figured out that I have to input ctrl+z so I can stop the program, I also printed the value of EOF and it's -1. However, when I enter -1 instead of ctrl+z the program continues to execute, and I want to understand why. Thank you!
回答1:
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);
}
回答2:
The getchar()
function returns either the numeric value of the character that was just entered (treated as an unsigned char
, so it's never negative), or the special value EOF
which indicates that there is no more input.
Windows uses Control-Z to trigger and end-of-file condition, which causes getchar()
to return the value EOF
. But EOF
is not a character value; it's specifically chosen to be a value that cannot be a character value.
End-of-file is a condition, not a value. EOF
is a numeric value, but not a character value; it's the value returned by getchar()
to indicate that input is in an end-of-file condition (or an error condition).
(If you want to read integer values, positive or negative, you need to read a single character at a time and then compute the integer value that the character sequence represents. The integer value -1
can be entered as the character '-'
followed by the character '1'
. C has various functions, like atoi
and the *scanf
family, that can do that conversion.)
回答3:
EOF isn't a 'value'. It is a sentinel defined by the stdio
library.
Ctrl/z is a keystroke, that is interpreted by the terminal driver and causes it to notify end of stream to the application reading from it, which causes C read()
to return zero, which causes getchar()
to return EOF.
The corresponding keystroke on Unix, Linux, etc, is Ctrl/d.
回答4:
You need to change the logic just a bit:
#include <stdio.h>
int main() {
int c;
int done = 0;
while (!done)
{
c = getchar();
if(c != '-')
putchar(c);
else
{
c = getchar();
if (c == '1')//this is an EOF
{
done = 1; // and probably putchar the EOF
}
else
{
putchar('-');
putchar(c);
}
}//else
}//while
return 0;
}
来源:https://stackoverflow.com/questions/46534511/value-of-eof-under-windows