Appending ints to char* and then clearing
-
12-09-2019 - |
Question
I'm working on a project using an Arduino and as such, I'm reading from a serial port (which sends int
s). I need to then write this serial communication to an LCD, which takes a char*
.
I need to read several characters from the serial port (two integers) into a string. After both have been received, I then need to clear the string to prepare for the next two characters.
TLDR: How do I append an int
to a char*
, and then clear the string after it has two characters?
Solution
A char is a single character, whereas a char* can be a pointer to a character or a pointer to the first character in a C string, which is an array of chars terminated by a null character.
You can't use a char to represent an integer longer than 1 digit, so I'm going to assume you did in fact mean char*.
If you have
char buffer[10];
then you can set buffer
to a string representing an int n
with sprintf
sprintf(buffer, "%d", n);
And when you're done with it, you can clear the string with
sprintf(buffer, "");
Hope that's what you were asking for, and good luck!
OTHER TIPS
You can't read into a char *, it is a pointer. You can read into the memory pointed to by the pointer, provided it points to something valid. As for clearing, it's not obvious what you mean by that.
Bottom line is that you need to post some actual code that attempts to do what you want, and ask about that.