简体   繁体   中英

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?

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.

std::ostringstream oss;
oss << t;
std::string s = "Temperature is " + oss.str();

Then you can use either the string or the c_str() of it (as const char* ).

If, for some reason, you don't have standard library, you can also use snprintf() et. al. (printf-variants), but then you need to do the buffer management yourself.

For the sake of completeness, C++20 introduces std::format for fluent string formatting of this sort:

#include <format>
#include <iostream>
#include <string>

int main() {
    float t = 30.2f;
    std::string s = std::format("Temperature is {}!\n", t);
    std::cout << s;
}

Do note that compiler support for the format library is still underway. GCC does not yet support it, and Clang only has experimental support 1 in 14.0+.

1 requires LLVM to be compiled with -DLIBCXX_ENABLE_INCOMPLETE_FEATURES=ON

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