gpt4 book ai didi

c - 使用strtod后如何将double值转换为char数组?在C中

转载 作者:行者123 更新时间:2023-11-30 19:29:16 25 4
gpt4 key购买 nike

例如,转换包含以下内容的字符串字符:

{x1 5.12 x2 7.68 x3}

double 值已转换为:

0.0000005.1200000.0000007.6800000.000000

如何转换这些 double 值,以便它创建一个应该是的字符数组:

{0.000000,5.120000,0.000000,7.680000,0.000000}

我一直在到处寻找进行此转换的方法,但似乎没有任何效果。如果有人可以提供代码来进行此转换。这些是我的代码:

void exSplit(char newEx[50]){             //newEx[50] contains {x1 5.12 
x2 7.68 x3}

char *delim = " ";
char *token = NULL;
char valueArray[50];
char *aux;
int i;

for (token = strtok(newEx, delim); token != NULL; token =
strtok(NULL, delim))
{
char *unconverted;
double value = strtod(token, &unconverted);

printf("%lf\n", value);

}

}

最佳答案

您可以使用scanf来扫描 float 。如果找到 float ,则将其打印到结果字符串中。如果找不到 float ,则将零打印到结果字符串中。

它可能看起来像:

#include <stdio.h>
#include <string.h>

int main(void) {
char newEx[] = "{x1 5.12 x2 7.68 x3}";
char *token;
char result[100] = "{";
char temp[100];
int first = 1;
float f;

for (token = strtok(newEx, " "); token != NULL; token = strtok(NULL, " "))
{
if (first != 1)
{
strcat(result, ",");
}
first =0;
if (sscanf(token, "%f", &f) == 1)
{
sprintf(temp, "%f", f);
}
else
{
sprintf(temp, "0.000000");
}
strcat(result, temp);
}
strcat(result, "}");
printf("%s\n", result);

return 0;
}

输出:

{0.000000,5.120000,0.000000,7.680000,0.000000}

注意:为了使上面的代码示例简单,没有检查缓冲区溢出。在实际代码中,您应该确保 sprintstrcat 不会溢出目标缓冲区。

关于c - 使用strtod后如何将double值转换为char数组?在C中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53139700/

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