2014-01-22 119 views
-1

当我在C++中连接时遇到了麻烦,我有一个浮点数值转换为字符数组,然后我尝试在该值前追加一些文本,但即时获取“ ?”作为输出,下面的代码:字符串与sprintf连接

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); 
+3

您确定您不打算将其标记为'C'吗? – bstamour

+2

你为什么用这个'dtostrf()'函数打扰?你应该可以做'sprintf(_outbuffer,“VL%6.2f”,voltage);'(你可能需要弄乱那个格式说明符才能以你想要的方式显示浮点数)。另外考虑使用'snprintf()',这样你不会溢出'_outbuffer'。 – Praetorian

+1

实际确定[tag:c]或[tag:C++] !!下压压力,因为它的问题不适合[标签:C++] ...任何你不能使用'std :: string'或其他C++标准库类的原因,如上所述? –

回答

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!" 

因此,对于您的情况,您可以使用这样的:

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>

+0

@RemyLebeau THX,很好的答案。那时我太懒惰了,希望一个> 2000的代表用户能够应付插值...... –

+1

我不关注代表,你永远不知道谁会在将来看到它。 –

+0

@RemyLebeau公平的论点... –

0

尝试strcat的

char v[15 + 1]; 
v[15] = 0; 
dtostrf(voltage, 6, 2, v); 
strcpy(_outbuffer, "VL"); 
strcat(_outbuffer, v); 

另外,作为suspectus建议,用sprintf。