【发布时间】:2019-06-12 19:33:03
【问题描述】:
我正在为 Uni 做一些工作并编写了一个程序,它将整数存储在一个 char 数组中,并将它们转换为它们的 ASCII 值并在最后打印它们。我的代码之前没有工作,只有当我在我的 scanf 行中将“%c”更改为“%i”时才开始工作。我的问题:当我想将这些数字存储在 char 数组而不是 Int 数组中时,为什么它必须是“%i”。谢谢!
我的代码:
#include <stdio.h>
int main()
{
int i; /counter
char numbers[12];
printf("Please enter 12 Numbers\n");
for(i = 0; i < 12; i++){
printf("please enter the %i. Number\n", i+1);
scanf("%i", &numbers[i]);// <-- changed "%c" to "%i" and it worked.why?
}
for(i = 0; i < 12;i++){
printf("The %i.ASCII value is %i and has the Char %c\n", i+1, numbers[i], numbers[i]);
}
return 0;
}
【问题讨论】:
-
这是未定义的行为。
%i用于int,但您尝试阅读char。你试过%hhi吗? -
请发布使用的输入示例和所需的输出。
-
他们可能希望您通过 %d 或 %i 将数字读取为
int,然后将int转换为char。不要用 %hhi 直接将其存储在char中,因为然后 scanf 会处理转换。