[英]Storing Integers in an Char Array in C
Im doing some work for Uni and wrote a programm which stores Integers in an char Array and converts them to their ASCII Values and prints them at the end. 我为Uni做一些工作,并编写了一个程序,将整数存储在char数组中,并将其转换为ASCII值并在最后打印出来。 My code did not work before and only started working when i changed "%c" to "%i" in my scanf line. 我的代码之前没有工作,只有在我在scanf行中将“%c”更改为“%i”时才开始工作。 My question: Why does it have to be "%i" when i wanna store those Numbers in an char Array and not an Int Array. 我的问题:当我想将这些数字存储在char数组而不是Int数组中时,为什么必须为“%i”。 Thanks! 谢谢!
My code: 我的代码:
#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;
}
%c
is for reading a single character. %c
用于读取单个字符。 So for example if you type in "123"
, scanf
will read '1'
into the char
variable and leaves the rest in the buffer. 因此,例如,如果您键入"123"
, scanf
将在char
变量中读取'1'
,并将其余的保留在缓冲区中。
On the other side %i
is the specifier for int
and will therefore lead to undefined behavior when trying to read in a char
. 另一方面, %i
是int
的说明符,因此在尝试读取char
时将导致未定义的行为。
I think what you are looking for is the %hhi
specifier, which reads a number into a char
variable. 我认为您正在寻找的是%hhi
说明符,该说明符将数字读入char
变量。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.