将int数组转换为char数组

Cra*_*der 9 c

我有一个整数数组说int example[5] = {1,2,3,4,5}.现在我想使用C而不是C++将它们转换为字符数组.我该怎么做?

Jer*_*myP 9

根据您的真实需要,这个问题有几种可能的答案:

int example[5] = {1,2,3,4,5};
char output[5];
int i;
Run Code Online (Sandbox Code Playgroud)

直接复制给出ASCII控制字符1 - 5

for (i = 0 ; i < 5 ; ++i)
{
    output[i] = example[i];
}
Run Code Online (Sandbox Code Playgroud)

字符'1' - '5'

for (i = 0 ; i < 5 ; ++i)
{
    output[i] = example[i] + '0';
}
Run Code Online (Sandbox Code Playgroud)

表示1 - 5的字符串.

char stringBuffer[20]; // Needs to be more than big enough to hold all the digits of an int
char* outputStrings[5];

for (i = 0 ; i < 5 ; ++i)
{
    snprintf(stringBuffer, 20, "%d", example[i]);
    // check for overrun omitted
    outputStrings[i] = strdup(stringBuffer);
}
Run Code Online (Sandbox Code Playgroud)

  • 如果整数大于'9'怎么办?"10"以上的整数不会转换为char格式. (3认同)