使用%d和%c将字符存储到整数变量中,反之亦然

时间:2018-09-24 09:53:01

标签: c

我对以下内容毫无疑问,因为在两种情况下它们实际上都存储为int类型。

int a; // combination 1
scanf("%d", &a); // suppose input is 65
printf("%c", a); // prints 'A'
printf("%d", a); // prints 65

char a; // combination 2
scanf("%c", &a); // suppose input is 'A'
printf("%c", a); // prints 'A'
printf("%d", a); // prints 65

我也理解这一点,因为char只能以字符形式存储第一个数字,因此在输入过程中,第一个'6'之后的任何内容都将被忽略。

char a; // combination 3
scanf("%c", &a); // suppose input is 65
printf("%c", a); // prints '6'
printf("%d", a); // prints 54 which is the ASCII value of '6'

但是我对理解这里发生的事情有疑问:

int a; // combination 4
scanf("%d", &a); // suppose input is 'A' (in fact any letter, upper or lower case)
printf("%c", a); // prints this symbol ╗
printf("%d", a); // prints 2

如前所述,无论输入哪个字母或大小写,它都显示相同的printf结果。所以我很困惑!

我还应该提到我对组合4的关注是因为我试图为int定义一个switch变量,该变量可以比较字母和数字的大小写,从而希望将所有内容转换变成int形式。使用char可变类型的作品,但这并不理想,因为它将任何2位数字与该数字中的第一位相同。

EDIT :因此,我发现scanf在组合4中基本上什么也不做。我想知道的是为什么当另三种组合不能使用scanf时的详细说明。工作。

1 个答案:

答案 0 :(得分:0)

在这种情况下,scanf跳过阅读字符。运行这个简单的测试。

int a; // combination 4
scanf("%d", &a); // suppose input is 'A' (in fact any letter, upper or lower case)
if(scanf("%d", &a) == 1) //to check character read or not
    printf("input: %d\n", a);
else 
    printf("Character skipped");
printf("%c", a); // prints this symbol ╗
printf("%d", a); // prints 2

输出:     跳过字符0