为什么我不能在C中找到EOF的值?
我正在阅读“C语言程序设计语言”一书,并且有一个练习要求validation表达式getchar() != EOF
返回1或0.现在我被要求做的原始代码是:
int main() { int c; c = getchar(); while (c != EOF) { putchar(c); c = getchar(); } }
所以我想把它改成:
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(); } }
书中的答案是:
int main() { printf("Press a key\n\n"); printf("The expression getchar() != EOF evaluates to %d\n", getchar() != EOF); }
你能告诉我为什么我的方式不起作用吗?
因为如果c
是EOF
,则while
循环终止(或者甚至不会启动,如果在键入的第一个字符上已经是EOF
)。 运行循环的另一次迭代的条件是c
不是 EOF
。
显示EOF的值
#include int main() { printf("EOF on my system is %d\n", EOF); return 0; }
EOF在stdio.h中定义为-1
通过在Unix中按ctrl + d和在Windows中按ctrl + c,可以通过键盘触发EOF。
示例代码:
void main() { printf(" value of getchar() != eof is %d ",(getchar() != EOF)); printf("value of eof %d", EOF); }
输出:
[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]#
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.
把它变成c!= EOF而不是。 因为您要打印表达式的结果而不是字符。
在你的程序中,你正在从std输入读取字符为c = getchar();
这样你就可以获得按下的键的ascii值,它永远不会等于EOF。
因为EOF是文件结束。
更好的是你尝试打开任何现有的文件并从文件中读取,所以当它到达文件结束(EOF)时,它将退出while循环。
那本书的答案是:
int main() { printf("Press a key\n\n"); printf("The expression getchar() != EOF evaluates to %d\n", getchar() != EOF); }
尝试理解程序,它得到一个键,它不等于EOF所以它应该总是打印“表达式getchar()!= EOF计算结果为0”。
希望能帮助到你…….