PrintEx icon indicating copy to clipboard operation
PrintEx copied to clipboard

Bad handling of "-0" flags.

Open SandorDobos opened this issue 5 years ago • 0 comments

PrintEx doesn't handle format strings like "%-05d" according to the printf(3) manual page:

If the 0 and - flags both appear, the 0 flag is ignored. 
...  
A - overrides a 0 if both are given.

This results in very bad outputs:

#include <PrintEx.h>

void setup() {
  Serial.begin(115200);
  PrintEx serial = Serial;

  // according the printf(3) manual on handling '-' and '0' flags 
  // the outputs below are bad:
  
  // outputs: "[-3000]", expected: "[-3   ]"
  serial.printf("[%-05d]\n", -3);

  // outputs: [30000], expected: "[3    ]"
  serial.printf("[%-05d]\n", 3);
}

void loop() {
  // no op
}

The fix is as simple as modifying 181. line of PrintExtension.cpp from:

if( formatTest( format, CHAR_ZERO ) )  pad |= PAD_ZERO;

to:

// formatTest should been always called to step over ignored 0s
if( formatTest( format, CHAR_ZERO ) && pad == 0)  pad |= PAD_ZERO;

(I am sorry but have no time to create a pull request.)

SandorDobos avatar Feb 07 '21 22:02 SandorDobos