我正在为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;
}
答案 0 :(得分:1)
%c
用于读取单个字符。因此,例如,如果您输入"123"
,则scanf
会将'1'
读入char
变量,并将其余的保留在缓冲区中。
另一方面,%i
是int
的说明符,因此在尝试读取char
时将导致不确定的行为。
我认为您正在寻找的是%hhi
修饰符,该修饰符将数字读入char
变量中。