使用sprintf进行字符串连接 当我在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);
中的字符串串联很容易,只需使用使用sprintf进行字符串连接 当我在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++,c,arduino,C++,C,Arduino,中的字符串串联很容易,只需使用+运算符: 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 <<
+
运算符:
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!"
std::ostringstream oss;
oss试试strcat
char v[15 + 1];
v[15] = 0;
dtostrf(voltage, 6, 2, v);
strcpy(_outbuffer, "VL");
strcat(_outbuffer, v);
或者,正如怀疑论所建议的那样,使用sprintf。您确定不想将其标记为C
?为什么要费心使用此dtostf()
函数?你应该能做sprintf(_exputfer,“VL%6.2f”,电压)代码>(您可能需要弄乱格式说明符,才能按您想要的方式显示float)。也可以考虑使用<代码> SNPROTFF()<代码>,这样就不会超出<代码>对压力投反对票,因为这个问题不适合。。。你不能使用<代码> STD::String < /C>或其他C++标准库类的任何原因吗?@ ReMyLeBeAthTx,很好地增强了答案。我当时太懒了,希望一个>2000次重复的用户能够处理插值…我不注意重复,你永远不知道将来谁会看到它。
char v[15 + 1];
v[15] = 0;
dtostrf(voltage, 6, 2, v);
strcpy(_outbuffer, "VL");
strcat(_outbuffer, v);