I am getting an int value from one of the analog pins on my Arduino. How do I concatenate this to a String
and then convert the String
to a char[]
?
It was suggested that I try char msg[] = myString.getChars();
, but I am receiving a message that getChars
does not exist.
You can convert it to char* if you don't need a modifiable string by using: (char*) yourString. c_str();
Basically String type variable in arduino is character array, Conversion of string to character array can be done using simple toCharArray() function. Getting string value in character array is useful when you want to break single string into parts or get part of string.
One method to convert an int to a char array is to use sprintf() or snprintf(). This function can be used to combine a number of variables into one, using the same formatting controls as fprintf(). int sprintf ( char *buf, const char *format, ... ); int snprintf( char *buf, size_t n, const char *format, ... );
To convert and append an integer, use operator += (or member function concat
):
String stringOne = "A long integer: "; stringOne += 123456789;
To get the string as type char[]
, use toCharArray():
char charBuf[50]; stringOne.toCharArray(charBuf, 50)
In the example, there is only space for 49 characters (presuming it is terminated by null). You may want to make the size dynamic.
###Overhead
The cost of bringing in String
(it is not included if not used anywhere in the sketch), is approximately 1212 bytes of program memory (flash) and 48 bytes RAM.
This was measured using Arduino IDE version 1.8.10 (2019-09-13) for an Arduino Leonardo sketch.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With