之間我一直試圖解決它半天......沒有成功...功能的加入字符數組含附加的符號在
我有一個結構:
typedef struct s_iomodus {
const char* SENSOR;
const char* POSITION_1;
const char* SHOW_MI;
const char* POSITION_2;
const char* TYPE_1;
const char* TYPE_2;
const char* DESCRIPTION; // LOC Description of the
const int NRVALUES;
} iomodus_t;
iomodus_t iomodus[] = {
{ "Relay","WW_Tank","WW_Pumpe_An_Aus","NO_P2","NO_T1","NO_T2" ,"MAGNETIC", 1}, //D25 :
{ "Relay","Puffer_Tank","NO_SHOW","NO_P2","NO_T1","NO_T2" ,"SSR", 1}, //D26 :
{ "Relay","WW_Tank","Valve","Auslauf_unten","Zu","Auf" ,"MAGNETIC", 2}, //D27 :
其中i存儲所有引腳和位置,這是我送的話題MQTT服務器的所有現狀設置..
現在我有此數組中建立一個字符串在VOID SETUP其發送的
void setup()
{
Serial.begin(115200);
MQTTclient.setServer(server, 1883);
MQTTclient.setCallback(callback);
Ethernet.begin(mac, ip);
// Allow the hardware to sort itself out
delay(1500);
const char *c_topic = concat_strings(iomodus[i].POSITION_1,iomodus[i].SENSOR, iomodus[i].POSITION_2);
Serial.println(c_topic);
MQTTclient.publish(c_topic, iomodus[i].VERSION);
}
我的問題是...該功能沒有製作正確的字符串 它不在中間添加「/」! 它應該是這樣的字符串: 「MQTTTOPIC_PREFIX/TEXT_str1/TEXT_str2/TEXT_str3」 或 「MQTTTOPIC_PREFIX/TEXT_str1/TEXT_str2/TEXT_str3/TEXT_str4」 如果STR4是存在/不爲空
const char *concat_strings(const char *str1, const char *str2, const char *str3,const char *str4)
{
// define a buffer
static char result[MAX_CONCAT_LEN] = {0};
// counter part
int i = 0;
const char *slash = {"/"};
const char *PREF= {MQTTTOPIC_PREFIX};
size_t len = strlen(PREF)+strlen(str1)+strlen(str2)+strlen(str3);
// loop until end of ID has reached or destination buffer is full
while(*PREF && i < MAX_CONCAT_LEN)
{result[i++] = *PREF++;}
// loop until end of string 1 has reached or destination buffer is full
while(*str1 && i < MAX_CONCAT_LEN)
{result[i++] = *str1++;}
// loop until end of string 2 has reached or destination buffer is full
while(*str2 && i < MAX_CONCAT_LEN)
{result[i++] = *str2++;}
if (str3==TRUE){
// loop until end of SLASH has reached or destination buffer is full
while(*slash && i < MAX_CONCAT_LEN)
{result[i++] = *slash++;}
while(*str3 && i < MAX_CONCAT_LEN)
{ result[i++] = *str3++;}
}
if (str4==TRUE){
// loop until end of SLASH has reached or destination buffer is full
while(*slash && i < MAX_CONCAT_LEN)
{result[i++] = *slash++;}
while(*str4 && i < MAX_CONCAT_LEN)
{ result[i++] = *str4++;}
}
result[len+1] = 0;
return result;
}
所以即使我這樣做...它不會添加「/」,並且不想識別,如果str3或str4是假...
請問,什麼是最簡單的方法來加入數組和如果str3或str4可用,則添加「/」(str1和str2始終存在)
預先感謝您!
這將是一個容易得多,如果你可以使用'的std :: string's。你可以使用它們嗎? – NathanOliver
@NathanOliver我很想首先提出同樣的建議。我認爲[tag:arduino]不同,它並不是真正的標準C++。 –
_ @ Max_爲什麼不簡單地使用['strcat()'](http://en.cppreference.com/w/c/string/byte/strcat)? –