This is the biggest problem with String. How can a beginner, for whom c-strings are allegedly too hard to understand (??), be expected to be careful about String's memory issues? Wouldn't it be easier to learn about c-strings than to learn about dynamic memory allocation and about why it is usually better avoided on a microcontroller?
@dazza000 You are thinking like a user of higher-level languages, that often tend to be dynamically typed. There's nothing wrong with that... as long as you are indeed using such a language. Let us forget about String for a while. In C, a string (lowercase) is just an array of numbers. Each number is interpreted as an ASCII symbol. The string "ABC"
actually contains 4 numbers: 0x41, 0x42, 0x43, 0x00
. There is nothing in the string itself that contains letters. The last zero, by the way, is the terminating null: it tells the string-handling functions that the string is complete and contains no more characters.
So, what are you trying to do? You want to convert 3 integers into a single string containing the concatenation of the ASCII values of each digit of each number, in decimal.
Note that
124 == 0174 == 0x7C
Choosing decimal is both arbitrary and relevant: same number, different ASCII output.
You can make 3 buffers with itoa()
and concatenate them into a single string; you can make it extra-hard and write bespoke code for everything; but why not use sptintf()
and do everything in one go, the easy way, and without the infamous String class?
/* First, we make a buffer large enough to hold 3 fat integers
* and a terminating null.
*/
char reading[20];
/* Second, we populate our string with sprintf() */
sprintf (reading, "%d%d%d", a0, a1, a2);
/* Third (optional), we do something with our new string */
Serial.print("The string is ");
Serial.print(reading);
Serial.print("\n");
If you have negative integers, you will have minus signs mixed in between your digits. You can change the output by changing the format string (i.e. "%d%d%d"
).
Type
man 3 printf
if you want the whole story.
sprintf()
will have you covered for decimal (signed and unsigned), hexadecimal and octal. If you want something special (say, base 5 or base 13), then you have to use itoa()
and concatenate buffers.