gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 21:05:49 25 4
gpt4 key购买 nike

我理解以下内容没有问题,因为在这两种情况下它们实际上都存储为 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 的原因是因为我试图为 switch 定义一个 int 变量,它可以比较字母和数字的大小写,从而希望将所有内容都转换为 int 形式。使用 char 变量是可行的,但它并不理想,因为它将任何 2 位数字视为与该数字中的第一个数字相同。

编辑:所以我发现基本上 scanf 在组合 4 中什么也不做。我想知道的是为什么 scanf 不能以这种方式使用的详细解释,而其他三个组合工作。

最佳答案

在这种情况下,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

关于c - 使用 %d 和 %c 将字符存储到整数变量中,反之亦然,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52476710/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com