字符串连接在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'吗? – bstamour
你为什么用这个'dtostrf()'函数打扰?你应该可以做'sprintf(_outbuffer,“VL%6.2f”,voltage);'(你可能需要弄乱那个格式说明符才能以你想要的方式显示浮点数)。另外考虑使用'snprintf()',这样你不会溢出'_outbuffer'。 – Praetorian
实际确定[tag:c]或[tag:C++] !!下压压力,因为它的问题不适合[标签:C++] ...任何你不能使用'std :: string'或其他C++标准库类的原因,如上所述? –