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

时间:2018-11-04 10:14:25

标签: c arrays string type-conversion double

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

{x1 5.12 x2 7.68 x3}

将double值转换为:

0.0000005.1200000.0000007.6800000.000000

如何转换这些双精度值,以使其创建应为以下字符数组:

{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);

    }

}

1 个答案:

答案 0 :(得分:0)

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

它看起来像:

#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不会溢出目标缓冲区。