Converting float to char*

后端 未结 7 863
野性不改
野性不改 2021-02-04 01:54

How can I convert a float value to char* in C language?

7条回答
  •  天命终不由人
    2021-02-04 02:38

    char buffer[64];
    int ret = snprintf(buffer, sizeof buffer, "%f", myFloat);
    
    if (ret < 0) {
        return EXIT_FAILURE;
    }
    if (ret >= sizeof buffer) {
        /* Result was truncated - resize the buffer and retry.
    }
    

    That will store the string representation of myFloat in myCharPointer. Make sure that the string is large enough to hold it, though.

    snprintf is a better option than sprintf as it guarantees it will never write past the size of the buffer you supply in argument 2.

提交回复
热议问题