sprintf but only once.

What am I missing, it works for the first iteration..

void test() {

    char testBuffer[20];
    char boop[20];
    
      for (int i=0;i<=9;i++) {
        
        sprintf(boop,"%%%d16d",i);     
        sprintf(testBuffer,boop,i);

        Serial.println(boop);
        Serial.println(testBuffer);

        delay(200);
      }
}

Output:

%016d
0000000000000000
%116d

I expected 16 0's followed by 16 1's, then 2's etc. Arduino seems to crash, but succeeds the first time.

This:

%116d

Is a format specifier saying print an int padded with spaces to be 116 characters wide. Into a buffer that has space for 20 bytes. Hence the crash.

Not quite. You need to take into account the whole format string. I'm pretty sure that %%%d16d translates as:
%%=display the % symbol
%d=display an integer
16d=just display 16d.

markd833:
Not quite. You need to take into account the whole format string. I'm pretty sure that %%%d16d translates as:
%%=display the % symbol
%d=display an integer
16d=just display 16d.

Which is then used as a format specifier for another sprintf.

Consequently first time around the loop i=0...

sprintf(boop,"%%%d16d",i) => %016d
sprintf(testBuffer,boop,i) => 0000000000000000

Second time around the loop i=1...

sprintf(boop,"%%%d16d",i) => %116d
sprintf(testBuffer,boop,i) => 00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001

CRASH!

Ah, my mistake. I didn't quite spot that!

Hrm, thanks for the responses..

So no shortcut to padding with other chars then :frowning: