I have a function that returns a char array and I want that turned into a String so I can better process it (compare to other stored data). I am using this simple for that should work, but it doesn't for some reason (bufferPos
is the length of the array, buffer
is the array and item
is an empty String):
for(int k=0; k<bufferPos; k++){
item += buffer[k];
}
The buffer
has the right values and so does bufferPos
, but when I try to convert, for example 544900010837154, it only holds 54. If I add Serial.prints to the for like this:
for(int k=0; k<bufferPos; k++){
Serial.print(buffer[k]);
Serial.print("\t");
Serial.println(item);
item += buffer[k];
}
the output is this:
5
4 5
4 54
9 54
0 54
0 54
0 54
1 54
0 54
8 54
3 54
7 54
1 54
What am I missing? It feels like such a simple task and I fail to see the solution...
Visit https://www.arduino.cc/en/Reference/StringConstructor to solve the problem easily.
This worked for me:
Three years later, I ran into the same problem. Here's my solution, everybody feel free to cut-n-paste. The simplest things keep us up all night! Running on an ATMega, and Adafruit Feather M0:
And we get:
Hope this helps someone!
If you have the char array null terminated, you can assign the char array to the string:
As for your loop code, it looks right, but I will try on my controller to see if I get the same problem.
I have search it again and search this question in baidu. Then I find 2 ways:
1,
Be aware to that '\0' is necessary for char array ch.
2,
In this way, you also need to add the '\0' at the end of char array.
Also, strstream.h file will be abandoned and be replaced by stringstream
May you should try creating a temp string object and then add to existing item string. Something like this.