c++ - 使用 sprintf 进行字符串连接

标签 c++ c arduino

当涉及到 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);

最佳答案

中的字符串连接简单,只需使用 +运算符:

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/

相关文章:

python - raspberry pi 和 teensy 之间的串行通信(使用 UART/GPIO 引脚)

C++ 在 Sublime Text 2 中编译和运行

c++ - 未处理的异常。访问违规阅读位置

c++ - 带有可变参数模板的 SFINAE

C++11 vector 包含 2 个不同的子类,但不同时

c - 输出格式错误

c - 如何在c中传递没有第二个元素的数组?

c - 如何在 C 中对指向 char 的指针数组进行 qsort?

c++ - 根据数组检查值时 Arduino 出错

ajax - Arduino WebServer和socket.io