String的问题
本帖最后由 zoologist 于 2015-5-17 13:50 编辑折腾了一个晚上,比如我想从串口得到一个输入,然后再输出到串口上,然后写下面的程序
String comdata="";
void setup() {
// put your setup code here, to run once:
Serial.begin(9600);
}
void loop() {
// put your main code here, to run repeatedly:
while (Serial.available() > 0)
{
comdata += Serial.read();
delay(2);
}
if (comdata.length()>1) {Serial.println(comdata);comdata="";}
}
但是惊奇的发现,结果属下面这样(貌似把每个字符转为了char对应的数值)
如果想得到想要的结果,需要做一个强制转换
String comdata="";
void setup() {
// put your setup code here, to run once:
Serial.begin(9600);
}
void loop() {
// put your main code here, to run repeatedly:
while (Serial.available() > 0)
{
comdata +=(char)Serial.read();
delay(2);
}
if (comdata.length()>1) {Serial.println(comdata);comdata="";}
}
谁能帮我解释一下?谢谢! 你已經看到問題了吧.
String class 的特性, 當 operator "+" 之後是 numeric type, 會自動把數值先轉成 字符再加上去.
"1" 的數值就是 49, 由於 Serial.read() 的結果是 int type, 當你用 comdata += Serial.read() 時, comdata 是 String, Serial.read() 是 int, 就會執行 String "+" int 的 operation.當你輸入第一個字 "1" 時, 就會先把 "1" (int value 為 ASCII 值, 即 49) 轉成 "49", 然後再連接上去.之後都是一樣了.
當你加上 (char) 的轉換後, comdata += (char)Serial.read(), 就變成是 String "+" char 的 operation, 這時就不需要任何轉換而直接連上去了.
谢谢哈长知识 Super169 发表于 2015-5-17 03:44 static/image/common/back.gif
你已經看到問題了吧.
String class 的特性, 當 operator "+" 之後是 numeric type, 會自動把數值先轉成...
受教了:handshake
页:
[1]