views:

515

answers:

2

I'm working on a project using an Arduino and as such, I'm reading from a serial port (which sends ints). 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 (2 integers) into a string. After both have been received, I then need to clear the string to prepare for the next two characters.

tl;dr: How do I append an int to a char*, then clear the string after it has 2 characters?

A: 

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.

anon
My apologies, I didn't realise the difference between a char and a char*. I've changed my question to say char. Also, by clearing, I mean making the char completely blank (no values).
Ryan McCue
No, you don't mean a char either - a char is a single byte. Please post some code!
anon
+2  A: 

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!

Marquis Wang
It seems to work, but using `buffer = "";` gives me a compile error: "incompatible types in assignment of 'const char [1]' to 'char [10]'"
Ryan McCue
Hm. Sorry my C is a little rusty. Go with sprintf(buffer, "");
Marquis Wang
OK, that works, but buffer appears to be set to "49" (the ASCII code for 1). Any ideas?
Ryan McCue
Is this after you try to clear it?
Marquis Wang
No, this is before that. (Reworded my question too, it should be better now.)
Ryan McCue
My code is here, if it helps: http://pastie.org/502586
Ryan McCue
I can just use chr(19) on the computer (sending) end, which lets this code work, so accepting it. Thanks!
Ryan McCue