从字符串转换为无符号字符*叶垃圾
这是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;
}
这不仅仅是“老”。它包含冗余和缺陷。 (a)当'std :: string'已经缓存了长度时,你不需要遍历一个字符串来查找它的长度。所以这种方法是O(n)而不是O(1) - yikes! (b)字符串是二进制安全的,但是你的'strlen'长度计数技术不是。 .....总之,我们有很多原因,我们很久以前就放弃了这些东西;我们不只是因为时间的任意流逝才会这样做。另外,'strlen(someCString)'是“旧”,但是'strlen(aCPlusPlusString.c_str())'是愚蠢的。 – 2014-11-06 14:40:12
@LightnessRacesinOrbit你是对的,我一直把它从我的答案中删除:)最好不要再教这个了 – deW1 2014-11-06 15:03:16
你也需要串command.c_str()
复制到notification
:
notification = new char[length + 1];
strcpy(notification , command.c_str());
注意,'的sizeof(命令)'将*不*给你的字符串的长度。您需要使用['length'](http://arduino.cc/en/Reference/StringLength)成员函数。 – 2014-11-06 13:31:52
这就是问题所在!谢谢。你能否写一个答案,我会接受。 (我觉得自己像个白痴)。 – Chirantan 2014-11-06 13:36:28