当涉及到 C++ 上的串联时,我总是遇到麻烦,我有一个浮点值,我正在转换为字符数组,然后我试图在该值前面附加一些文本,但我得到一个“?”作为输出,代码如下:
int sensorValue = analogRead(A0);
float voltage= sensorValue * (5.0 / 421.0);
char v[6];
dtostrf(voltage, 6, 2, v);
sprintf(_outbuffer, "VL%s", v);
Serial.println(v);
Serial.println(_outbuffer);
最佳答案
c++ 中的字符串连接简单,只需使用 +
运算符:
std::string s1("Hello");
std::string s2("World");
std::string concat = s1 + s2; // concat will contain "HelloWorld"
如果您需要高级格式化功能或数字格式化,可以使用std::ostringstream
类:
std::ostringstream oss;
oss << 1 << "," << 2 << "," << 3 << ", Hello World!";
std::string result = oss.str(); // result will contain "1,2,3, Hello World!"
因此,根据您的情况,您可以使用:
int sensorValue = analogRead(A0);
float voltage = sensorValue * (5.0 / 421.0);
std::ostringstream oss;
oss << std::fixed << std::setw(6) << std::setprecision(2) << voltage;
std::string v = oss.str();
std::string _outbuffer = "VL" + v;
Serial.println(v.c_str());
Serial.println(_outbuffer.c_str());
注意:
要使用 iostream 操纵器函数(如提到的 std::setw()
等),您需要 #include <iomanip>
除此之外#include <ostringstream>
.
关于c++ - 使用 sprintf 进行字符串连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21294613/