Dear,
In the sprinf conversion specification %n$, n is an integer, e.g. $2$
n is 'hard coded' in the program.
I want to use a variable instead to print a variable number of digit to a LCD.
I tried to use string and constr char. No success.
Ideas ar welcome. Thanks.
Hello
%n is used to store in a variable the amount of characters that were written in the string by sprintf. This is not what you want, and it's rarely used.
You must use %d or similar, depending on the exact type of the variable.
See this : https://www.cplusplus.com/reference/cstdio/printf/
I am not entirely clear what you are trying to do, but you can specify the width parameter in a variable like this
void setup()
{
Serial.begin(115200);
char * value = "1234567890";
for (int n = 1; n < 8; n++)
{
Serial.printf("value is %.*s\n", n, value); //ESP32
}
}
void loop()
{
}
The output
value is 1
value is 12
value is 123
value is 1234
value is 12345
value is 123456
value is 1234567
Which board are you using -- UNO or ESP32?
OK, nice trick, learned (I hope) something today.
I was gonna suggest using sprintf to make the format string ahead of its use in the Serial.print statement.
Hey wait… Serial.printf? Learned something else. ![]()
edit: Oh, ESP32, never mind.
a7
a7
I'm using
#include <LiquidCrystal_I2C.h>
and a clipping of the code:
int rotEnPos = 0;
char cstr[16];
sprintf(cstr, "%3d", rotEnPos); //print 3 digits
lcd.setCursor(4, 1); //starting at bottom row position 4
lcd.print(cstr);
This works nicely, except that the three 3 digits are fixed
@UKheliBob: it seems that the class LiquidCrystal_I2C has no member printf
It will if it inherits from the Print class and you're on a platform whose Print class supports printf (i.e. ARM or ESP).
This is the game I had in mind:
char format[32];
char buffer[64];
int anInteger = 777;
byte digits;
void setup() {
Serial.begin(9600);
Serial.println("Hello printf Wolrd!\n");
// Serial.printf("%05d", anInteger); no printf in Serial? didn complle.
digits = 4;
sprintf(format, "like %c%c%d%c", '%', '0', digits, 'd');
sprintf(buffer, format, anInteger);
Serial.println(buffer);
Serial.print("\n\n");
digits = 6;
sprintf(format, "like %c%c%d%c", '%', '0', digits, 'd');
sprintf(buffer, format, anInteger);
Serial.println(buffer);
Serial.print("\n\n");
digits = 7;
sprintf(format, "like %c%c%d%c", '%', '0', digits, 'd');
sprintf(buffer, format, anInteger);
Serial.println(buffer);
Serial.print("\n\n");
}
void loop() {
}
HTH
a7
Then you must use * as shown by HeliBob ( and as described in the link I gave )
sprintf(cstr, "%*d", 3, rotEnPos);
As the comment in the code says, it is an ESP32
sorry missed that comment. I'm using a Nano
Building the format string with sprintf() seems to be the obvious choice. I have seen that before. Sketch from @alto777 of Reply #8 in Wokwi: https://wokwi.com/arduino/projects/322451529929851476
/alto777 blushes.
THX!
a7
Dear,
It took me some time to digest your answers.
Now it works.
Tx for your support!