snprintf pad length specifier not working

Hello!

I am having trouble with the '*' specifier in printf, as follows:

  Serial.begin(9600);
  char buf[50];
  sprintf(buf, "|%-20s|", "HELLO");
  Serial.println(buf);

I get "|HELLO |" on the serial mon. All good. However, if I try:

  Serial.begin(9600);
  char buf[50];
  sprintf(buf, "|%-*s|", 20, "HELLO");
  Serial.println(buf);

I get a single "|" character.

What am I doing wrong? The same format spec gets me the result I want using gcc.

Thank you!

Please post a full example program that shows the problem.

void setup() {

  char buf[50];

  Serial.begin(9600);

  //print with hard-coded pad length, prints:   |HELLO               |
  sprintf(buf, "|%-20s|", "HELLO");
  Serial.println(buf);

  //clear buffer
  memset(buf, 0, sizeof(buf));

  //print with deferred pad length, prints:     |
  sprintf(buf, "|%-*s|", 20, "HELLO");
  Serial.println(buf);
  
}

void loop() {}

Looks to me that that 'feature' is not supported by the Arduino snprintf, similar to support for floating point.

I've tried below few variation as well and the result is the same; both only print the pipe

  sprintf(buf, "|%*s|", -20, "HELLO");
  Serial.println(buf);

When printing the buffer byte by byte, the second character is the null terminator

  for (uint8_t cnt = 0; cnt < sizeof(buf); cnt++)
  {
    if (buf[cnt] < 0x10)
      Serial.print(" 0x0");
    else
      Serial.print(" 0x0");
    Serial.print(buf[cnt], HEX);
  }

AVR Libc vfprintf()

...
Notes:

The variable width or precision field (an asterisk * symbol) is not realized and will to abort the output.

Ah. Thanks folks. Looks like we're hardcoding the length :frowning:

You could build the format string on the fly:

snprintf(format, sizeof(format), "|%%%ds|", -20);
snprintf(buffer, sizeof(buffer), format, "HELLO");