Hi, I need some help with my Arduino.
I wanted to create a string with a length of 3 characters.
and wanted to print this string on the LCD display.
these 3 characters will be an integer that can range between 0 and 999.
int number = 123 // range between 0 and 999
string a = number; // the string must always be 3 characters long.
lcd.print(a);
My problem is how do I define the string with only 3 characters of space? that is, even if the number only has 1 character I want the string to have 3. That is, when printing it would be ("clear","clear",3)
char myNumberToPrint[4] = ""; //has to have size of 4 to include '\0';
for(int theNumber = 0;theNumber<15;theNumber++){
snprintf(myNumberToPrint, sizeof(myNumberToPrint), "%d ", theNumber);
lcd.print(myNumberToPrint);
delay(100);
}
by using snprintf(), you can add two spaces after the %d and then these will be added if the strlength of the integer is too low. So if theNumber = 9, the lcd will print 9 with two spaces, but if theNumber = 123, the ldc will print 123 with no spaces.
This works because snprintf() will make sure that whatever "%d " is, it will only ever copy the first 3 characters to ensure the final char in myNumberToPrint is a '\0'
Sorry i've just seen that you want it in the format of:
" 1", " 10", "231"
i.e. white spaces before the number.
In order to do that, use the code in my previous reply and change the snprintf() line from: snprintf(myNumberToPrint, sizeof(myNumberToPrint), "%d ", theNumber);
to snprintf(myNumberToPrint, sizeof(myNumberToPrint), "%3d", theNumber);
and you will get it in the format you like