 # passing an INT to a function that expects a char array

I have the function

``````void lcdPrint(int x, int y, char const *msg) {
if (x < 0) x = (20-strlen(msg))/2;
lcd.setCursor(x,y);lcd.print(msg);
}
``````

But now I find that I want to pass an integer to it occasionally. How can I convert the integer so that this function will accept it. (c++ is still new to me)

Charlie

I guess I see how that relates to a int and a double, both numeric types, but I am trying to convert an integer to a char array that will be accepted by a function that depends on a char, so even if I get it into the function, not sure how to convert 365 to “365” Am I missing the point?

Ok, so are you saying that I need to create another function with the same name, but change the third parameter to an int and that way I can specify an integer or a char for that parameter without any further conversion. Sorry to be so thick.

I would still need to center the output (first line of the function) so it seems that it would have to be converted for that, or is there another way to center a 1 to 12 digit number in a 20 character lcd line?

You could take the log10 of the number you’re printing to see how many digits it would have.
Or convert it using “itoa” and then use strlen.

TolpuddleSartre: Or convert it using "itoa" and then use strlen.

Or convert it using "itoa" and then pass it to your original function.

gfvalvo:
Or convert it using “itoa” and then pass it to your original function.

{red-face}

Thank you very much.

Forget the log approach - the itoa approach is much simpler.

crchisholm: [...] and I didn’t know about itoa.

1. itoa(arg1, arg2, arg3); ------> itoa(int, buffer, base); 2. itoa stands for "integer to ASCII."

3. itoa() is a function which transforms the arg1 (an int value) into digits as many as required as demanded by arg3 (base: 10 or 16 or ...); each digit is replaced by its ASCII code; the resultant ASCII code (s) is saved in an character type array referred/pointed by arg2.

4. Example

``````arg1 (argument1) :    int x = 0x10A;
arg3                    :     10
Created digits are :     2, 6, 6                //because 0x10A (hexadecimal value) = 266
arg2                    :     char myArray;

Serial.print(myArray);      //Serial Monitor will show: 266
``````

5. Coding

``````void setup()
{
Serial.begin(9600);
int x = 0x10A;             // x could be any unknown value like x = analogRead(A3);

char myArray;   //should have some idea about the size of the input/output data
itoa(x, myArray, 10);
Serial.println(myArray);   //shows: 266

itoa(x, myArray, 16);
Serial.println(myArray);   //shows: 10a (10A)

}

void loop()
{

}
``````

void lcdPrint(int x, int y, char const *msg) {
if (x < 0) x = (20 - strlen(msg)) / 2;
lcd.setCursor(x, y); lcd.print(msg);
}

void lcdPrint(int x, int y, int value) {
char buffer;
itoa(buffer, value, 10);
lcdPrint(x, t, buffer);
}