我是(mis-)使用Arduino String類。我的整個程序:Arduino:字符串連接困難
void setup() {
Serial.begin(9600);
}
void loop() {
const String args[3] = {
"foo", "bar", "baz" };
String result = "";
Serial.println(result);
result += args[0];
Serial.println(result);
result += args[1];
Serial.println(result);
result += args[2];
Serial.println(result);
Serial.println();
}
此打印:
foo
foobar
foobarbaz
foo
foobar
foobarbaz
foo
foobar
foobarüÿ
foo
foobar
foobarüÿ
foo
foobar
foobar
foo
foobar
foobarüÿ
foo
foobar
foobarüÿ
foo
foobar
foobarüÿ
我不知道爲什麼它不只是始終打印:
foo
foobar
foobarbaz
什麼可能我是做錯了什麼?
更新:我試着向數組中添加第四個字符串。現在程序通過loop()
左右15次停止運行。
更新2:這裏是code爲String
追加操作:
const String & String::operator+=(const String &other)
{
_length += other._length;
if (_length > _capacity)
{
char *temp = (char *)realloc(_buffer, _length + 1);
if (temp != NULL) {
_buffer = temp;
_capacity = _length;
} else {
_length -= other._length;
return *this;
}
}
strcat(_buffer, other._buffer);
return *this;
}
更新3:如果我更換:
String result = "";
有:
String result = args[0];
問題消失。有趣。
嗯,爲什麼不使用std :: string? – 2011-04-26 00:28:52
這是在Arduino上可用嗎?我不認爲這是。 – 2011-04-26 01:51:59
arduino有一個STL端口:http://www.arduino.cc/cgi-bin/yabb2/YaBB.pl?num=1295132807,但是,就像作者說的那樣,你需要仔細觀察你的記憶。 – dusktreader 2011-06-01 23:32:41