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

标签 c arrays string type-conversion double

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

{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/

相关文章:

c - 为什么我无法创建此文件?

c - ncurses:警告:取消引用 ‘void *’ 指针

javascript - 数组操作/映射返回未定义

在 C 中复制结构元素与复制数组元素

使用 cout << 打印字符串时 CodeBlocks 中的 C++ 运行时错误

c - Linux子进程信号丢失

c - 发送文件套接字C linux

c - 指向仅存在于函数 C 中的变量

c++ - 使用 const cast 将 std 字符串转换为 char*

c - printf的实现