gpt4 book ai didi

c++ - 如何廉价地将 char 数组和数字合并在一起?

转载 作者:行者123 更新时间:2023-11-28 01:26:24 26 4
gpt4 key购买 nike

我有几个这样的数组和数字:

char *test = "bla";
char *test1 = "bla bla";
float test2 = 3.14;
int test3 = 556878;

我想按顺序将它们全部合并到一个字符数组中,但我不能使用像 snprintf 这样的东西,因为这段代码运行在内存非常宝贵的 Arduino 上。

预期结果:

char *merged = "blabla bla3.14556878";

解决此问题的最佳方法是什么?

最佳答案

使用itoa()ftoa()intfloat 值转换为字符串,然后使用strcat

itoa 将在 arduino 中工作。

下面提供了ftoa函数:

char buff1[10];
char buff2[10];

itoa(test3,buff1,10);
ftoa(test2,buff2,3);

void ftoa(float n, char *res, int afterpoint)
{
// Extract integer part
int ipart = (int)n;

// Extract floating part
float fpart = n - (float)ipart;

// convert integer part to string
itoa(ipart, res, 10);

int i = strlen(res);

// check for display option after point
if (afterpoint != 0)
{
res[i] = '.'; // add dot

// Get the value of fraction part upto given no.
// of points after dot. The third parameter is needed
// to handle cases like 233.007
fpart = fpart * pow(10, afterpoint);

itoa((int)fpart, res + i + 1, 10);
}
}

关于c++ - 如何廉价地将 char 数组和数字合并在一起?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53591324/

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