2014-11-06 93 views
1

這是C++新手問題。我有一個Arduino草圖以下代碼來傳輸藍牙低功耗UART通知。從字符串轉換爲無符號字符*葉垃圾

command是5個字符時,我在藍牙接收器端得到5個字符。但是,當我使用單個字符命令跟隨5個字符command時,接收到的是單個字符,後面是前一個command的最後3個字符。

實施例,

command-1,0t。我收到的是-1,0t。但下一個command只是r。我收到的是r,0t

這裏發生了什麼?我如何得到「r」?

int BLEsend(String command){ 
    byte length = sizeof(command);  
    unsigned char* notification = (unsigned char*) command.c_str(); // cast from string to unsigned char* 
    Serial.print(length); 
    BLE.sendData(UART_SEND, notification, length); 
    Serial.print("Notification Sent: "); Serial.println(command); 
    delay(100); 
    return 1; 
} 
+7

注意,'的sizeof(命令)'將*不*給你的字符串的長度。您需要使用['length'](http://arduino.cc/en/Reference/StringLength)成員函數。 – 2014-11-06 13:31:52

+0

這就是問題所在!謝謝。你能否寫一個答案,我會接受。 (我覺得自己像個白癡)。 – Chirantan 2014-11-06 13:36:28

回答

0

sizeof()不給你字符串的長度。

您可以改用int length = command.length();

另外command.size();也應該工作。

+0

這不僅僅是「老」。它包含冗餘和缺陷。 (a)當'std :: string'已經緩存了長度時,你不需要遍歷一個字符串來查找它的長度。所以這種方法是O(n)而不是O(1) - yikes! (b)字符串是二進制安全的,但是你的'strlen'長度計數技術不是。 .....總之,我們有很多原因,我們很久以前就放棄了這些東西;我們不只是因爲時間的任意流逝纔會這樣做。另外,'strlen(someCString)'是「舊」,但是'strlen(aCPlusPlusString.c_str())'是愚蠢的。 – 2014-11-06 14:40:12

+0

@LightnessRacesinOrbit你是對的,我一直把它從我的答案中刪除:)最好不要再教這個了 – deW1 2014-11-06 15:03:16

0

你也需要串command.c_str()複製到notification

notification = new char[length + 1]; 
strcpy(notification , command.c_str()); 
相關問題