简体   繁体   English

C 中的 int 到字符串转换的数组

[英]Array of int to string conversion in C

I'm trying to convert an array of integers into a string in C.我正在尝试将整数数组转换为 C 中的字符串。 FOr instance I have the following code:例如,我有以下代码:

 int number[] = {1,3,2,0};
 char c[5];
 for(int i = 0 ; i < 4; i ++ ){
        c[i] = number[i];
    }
printf("%s", c);

It however outputs smiley faces or hearts and I am not sure why.然而,它会输出笑脸或心形,我不知道为什么。

When you printf characters, it takes the ASCII symbol for that number.当您printf字符时,它采用该数字的ASCII 符号

Your numbers 1, 3, 2, 0 are SOH , ETX , STX , which are non-printable characters.您的数字 1、3、2、0 是SOHETXSTX ,它们是不可打印的字符。

Try the numbers 65, 66 for example, they are letters.例如,试试数字 65、66,它们是字母。

The code shown is not giving you any output as it will not compile.显示的代码没有给你任何 output 因为它不会编译。

It is hard to say what you want to archive but here you have an example:很难说你想要归档什么,但这里有一个例子:

int main(void)
{
    int number[] = {1,3,2,0};
    char c[sizeof(number) / sizeof(number[0]) + 1] = {0,};
    char d[sizeof(number) / sizeof(number[0])][10];

    for(int i = 0 ; i < 4; i ++ ){
        c[i] = number[i] % 10 + '0';
        snprintf(d[i], 10, "%d", number[i]);
    }
    printf("%s\n", c);

    for(int i = 0 ; i < 4; i ++ ){
        printf("%s\n",d[i]);
    }

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM