c语⾔char追加,如何在C中的char数组末尾添加char(零)?我是C语⾔的新⼿(我⽤的是delphi/pascal),尝试获取⼀些温度传感器值,并使其⼤⼩相等/固定,然后发送到MCU(使⽤arduino-ide),所以我必须使⽤C语⾔。
数据长度(strlen())可以是3(如5.3、0.9、0.0等)、4(如-4.2、19.8等)或5(如-15.6),以温度传感器为基础,代码以下;
char value[5]; // must be char in order to send to MCU
if ((temp_data>=temp_max){
fix_size(value,true); //Error part. writes: "EEEEE" to reach fix size: 5
} else {
dtostrf(temp_data, 0, 1, value);
fix_size(value,false); //I'll use this to send data to screen later..
}
我需要修正数据的⼤⼩(我试图在末尾加零),IAM试图在下⾯做;
char fix_size(char temp_char[5],bool err=false){
if(err){
temp_char= "EEEEE";
Serial.println(temp_char);
return temp_char;
}
int num = strlen(temp_char);
// If strlen is 5 then it is OK and strlen cannot be 2 and 1 because of my temp sensor data processing (dtostrf(temp_data, 0, 1, value)) so I only need to take care 3 and 4
switch (num) {
case 3:
temp_char[3] = "0";
temp_char[4] = "\0";
//0.0 would become 0.000
//5.4 would become 5.400
break;
case 4:
temp_char[4] = "\0";
//15.2 would become 15.20
//-7.4 would become -7.40
break;
// -15.3 is in right format already
} | E.g. I tried for 15.4 and get
c语言char的用法Serial.println(temp_char[0]); | 1
Serial.println(temp_char[1]); | 5
Serial.println(temp_char[2]); | .
Serial.println(temp_char[3]); | 4
Serial.println(temp_char[4]); | Ø
return temp_char;
}
但是,当我执⾏这个应⽤程序的时候,我把奇怪的字符作为Arduinoid(反问号、正⽅形等)的输出。
有什么问题?我怎样才能解决这个问题?或者你能建议更好的⽅法吗?现在谢谢……
注:这个问题的起源(问题)更多的是关于嵌⼊式系统,我已经问了另⼀个关于电⼦堆叠交换的问题,作为这个问题的参考(如果你想要/需要you can read here
)
编辑:我已经更正了编码
switch (num) {
case 3:
temp_char[4] = "0";
temp_char[5] = "0";
temp_char[6] = "\0";
//0.0 would become 0.000
//5.4 would become 5.400
break;
case 4:
temp_char[5] = "0";
temp_char[6] = "\0";
//15.2 would become 15.20
//-7.4 would become -7.40
break;
// -15.3 is in right format already
}
switch (num) {
case 3:
temp_char[3] = "0";
temp_char[4] = "\0";
//0.0 would become 0.000
//5.4 would become 5.400 break;
case 4:
temp_char[4] = "\0";
//15.2 would become 15.20
//-7.4 would become -7.40 break;
// -15.3 is in right format already }