Go Down

Topic: Reading the length of an array entry.. (Read 1 time) previous topic - next topic

b00lean

Hello..

lets say I have an array and I want to center the output on my 4x20 LCD.
Do I take the right path with this?

Code: [Select]
char hours[14][15] = {"eins","zwei","drei","vier","fuenf","sechs","sieben","acht","neun","zehn","elf","zwoelf","mittag","mitternacht"};

This is one of my arrays which I use on my LCD.

If I try to set up the function to get the length of each entry I get a compiler error:

In function 'void StringLength(int, int)':
error: request for member 'size' in 'hours[1]', which is of non-class type 'char [15]'

And this is the code I try to use:
Code: [Select]
pos = (20-hours[1].size())/2;

Where did I go wrong?

Thanks for any help!

-andreas

mem

#1
Nov 07, 2008, 06:58 pm Last Edit: Nov 07, 2008, 06:59 pm by mem Reason: 1
Hi Andreas, because your string lengths vary, its much more efficient to make an array of string pointers.

char *hours[] = {"eins","zwei","drei","vier","fuenf","sechs","sieben","acht","neun","zehn","elf","zwoelf","mittag","mitternacht"};

usage:
 print(hours[0]);  // will print eins
 print(hours[1]); // will print zwei

//to get the position of zwei:
int pos = strlen(hours[1]) /2;  // strlen returns the length of the string

b00lean

#2
Nov 07, 2008, 07:32 pm Last Edit: Nov 07, 2008, 07:36 pm by b00lean Reason: 1
duh! I thought too much about c++ ;) Thanks for the hint!

PS: works like a charm!

mikalhart

Quote
int pos = strlen(hours[1]) /2;  // strlen returns the length of the string


I'm a little confused by this.  What is the purpose of "pos" exactly?

Mikal

b00lean

#4
Nov 07, 2008, 09:47 pm Last Edit: Nov 07, 2008, 09:51 pm by b00lean Reason: 1
assuming I have a LCD Display (4x20) and I need to center the text messages on each row.. that's why I do the following

"20 minus the length of my string and then divide by 2 equals the starting position of the string"

Code: [Select]
int pos = (20-strlen(hours[count]))/2;
lcd.cursorTo(2, pos);
lcd.printIn(hours[count]);



-andreas

mikalhart

#5
Nov 07, 2008, 10:00 pm Last Edit: Nov 07, 2008, 10:01 pm by mikalhart Reason: 1
ah, yes of course; nice!

Mikal

Go Up