简体   繁体   中英

How to convert double value into an char array after using strtod? in C

For example, converting a character of string that contains:

{x1 5.12 x2 7.68 x3}

to double values have been converted to:

0.0000005.1200000.0000007.6800000.000000

How do I convert these double values such that it creates a character array that should be:

{0.000000,5.120000,0.000000,7.680000,0.000000}

I have been looking everywhere to do this conversion and nothing seems to work. If someone may please provide a code to do this conversion. These are my codes:

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

    }

}

You can use scanf to scan for a float. If a float is found, you print it to the result string. In no float is found, you print the zeros to the result string.

It could look like:

#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;
}

Output:

{0.000000,5.120000,0.000000,7.680000,0.000000}

Note: To keep the code example above simple, there is no check for buffer overflow. In real code you should make sure that sprint and strcat wont overflow the destination buffer.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM