我正在阅读《C编程语言》一书,其中有一个练习要求验证表达式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 keynn");
printf("The expression getchar() != EOF evaluates to %dn", getchar() != EOF);
}
你能解释一下为什么我的方法不管用吗?
因为如果c
是EOF
,则while
循环终止(或者甚至不会开始,如果输入的第一个字符已经是EOF
)。运行另一次循环的条件是c
不是 EOF
。
显示EOF
#include <stdio.h>
int main()
{
printf("EOF on my system is %dn", EOF);
return 0;
}
EOF通常在stdio.h中定义为-1
EOF可以通过键盘触发,在Unix中按ctrl+d,在Windows中按ctrl+c。
示例代码:
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 keynn");
printf("The expression getchar() != EOF evaluates to %dn", getchar() != EOF);
}
试着理解这个程序,它得到一个键,它不等于EOF,所以它应该总是打印"表达式getchar() != EOF的计算结果为0"。
希望能有所帮助.......