Search code examples
c++stm32

How to concat string and float


I have a simple variable:

float t = 30.2f;

How do I add it to a string?

char* g = "Temperature is " + h?

Any guaranteed way (I don't have Boost for instance, and unsure of what version of c++ I have) I can get this to work on a microcontroller?


Solution

  • For simple cases, you can just use the std::string class and the std::to_string function, which have both been part of C++ for a long time.

    #include <string>
    #include <iostream>
    
    int main()
    {
      float t = 30.2;
      std::string r = "Temperature is " + std::to_string(t);
      std::cout << r;
    }
    

    However, std::to_string doesn't give you much control over the formatting, so if you need to specify a field width or a number of digits after the decimal point or something like that, it would be better to see lorro's answer.

    If you have an incomplete implementation of the C++ standard library on your microcontroller so you can't use the functions above, or maybe you just want to avoid dynamic memory allocation, try this code (which is valid in C or C++):

    float t = 30.2;
    char buffer[80];
    sprintf(buffer, "Temperature is %f.", t);
    

    Note that buffer must be large enough to guarantee there will never be a buffer overflow, and failing to make it large enough could cause crashes and security issues.