scanf(“%c”,..)和getchar()之间的区别

时间:2013-08-28 14:34:17

标签: c io

在测试之前,我始终认为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 type和char input

由于EOF在-1类型中为int,我也尝试使用scanf("%d",&i);替换scanf("%c",&i),只是获得相同的输出。

我很困惑。有人可以帮我解释一下吗?

---------------------------------- EDIT ------------ -----------------------------------

我想知道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

2 个答案:

答案 0 :(得分:3)

第一个值可能是未定义的行为。除非i返回1,否则您不能依赖scanf()具有值。

特别是scanf(),您似乎会将扫描值(根据第一个参数中的格式说明符转换字符)与函数调用的返回值混淆。

当然,对于getchar(),这种区别不存在,因为只有具有返回值。

答案 1 :(得分:3)

您的比较未完全设置i,因为它涉及未定义的行为(UB)。

int i;            // the value of i could be anything
scanf("%c",&i);   // At most, only 1 byte of i is set, the remaining bytes are still unknown.
printf("%d\n", i);// Your are printing 'i' whose value is not fully determined.

你试过吗

char ch;
int y = scanf("%c",&ch);
printf("%d\n", ch);
if(ch == EOF)

即使输入不是EOF,您也可能会进行匹配。如果您在char中扫描了值为255的字符,那么字符将取2位赞美的8位值-1。比较符号将扩展8位-1以匹配int大小,您将匹配-1 (假设:2s恭维整数,8位字节,EOF == -1,char被签名)。

正确的EOF测试

int y = scanf("%c",&ch);
if (y == EOF)

注意:getchar()&amp; scanf()返回EOF表示文件结束 I / O错误。对ferror(stdin)的后续检查区分了这一点。