【发布时间】:2013-08-28 14:34:16
【问题描述】:
在我测试之前,我一直认为scanf("%c" , &addr); 等于getchar():
#include<stdio.h>
int main()
{
int i;
scanf("%c",&i);
printf("%d\n", i);
if(i == EOF)
printf("EOF int type and char input\n");
i =getchar();
printf("%d\n", i);
if(i == EOF)
printf("EOF int type and char input\n");
}
当我使用“Ctrl+D”两次时,我得到了输出:
-1217114112
-1
EOF int 类型和字符输入
由于 EOF 在 int 类型中是 -1 ,我也尝试使用 scanf("%d",&i); 替换 scanf("%c",&i) ,得到相同的输出。
我很困惑。谁能帮我解释一下?
----------------------编辑------------ ----------------------------------
我想知道 Ctrl+D 的scanf("%c",i) 的行为,我做测试:
#include<stdio.h>
int main()
{
int i;
int j;
j = scanf("%c",&i);
printf("%c\n", i);
printf("%d\n", j);
if(i == EOF)
printf("EOF int type and char input");
i =getchar();
printf("%d\n", i);
if(i == EOF)
printf("EOF int type and char input");
}
输出:
k // If the scanf set 1 byte in i , why here print 'k' ?
-1
-1
EOF int type and char input
【问题讨论】:
-
输出中的
k是i中的随机垃圾值,在您尝试通过将其传递给scanf()以将其作为char处理而不是int就是这样。当scanf()遇到EOF(要读取零个字符)时,它根本不会分配给变量;它只返回 EOF。如果j不是 1,那么对于i中的内容,您无话可说;它的值是不确定的(但可能与您在函数调用之前开始的相同 - 但在示例代码中,这是未定义的,因为i未初始化)。