gpt4 book ai didi

将 int 数组转换为 char 数组

转载 作者:太空狗 更新时间:2023-10-29 16:53:36 24 4
gpt4 key购买 nike

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

最佳答案

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

int example[5] = {1,2,3,4,5};
char output[5];
int i;

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

for (i = 0 ; i < 5 ; ++i)
{
output[i] = example[i];
}

字符'1' - '5'

for (i = 0 ; i < 5 ; ++i)
{
output[i] = example[i] + '0';
}

代表 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);
}

关于将 int 数组转换为 char 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4712737/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com