在C中的Char数组中存储整数

时间:2019-01-18 14:03:54

标签: c arrays

我正在为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;
}

1 个答案:

答案 0 :(得分:1)

%c用于读取单个字符。因此,例如,如果您输入"123",则scanf会将'1'读入char变量,并将其余的保留在缓冲区中。

另一方面,%iint的说明符,因此在尝试读取char时将导致不确定的行为。

我认为您正在寻找的是%hhi修饰符,该修饰符将数字读入char变量中。