Chris--A / PrintEx

An extension to the Arduino Print library, and much, much more...
GNU General Public License v3.0
61 stars 16 forks source link

Bad handling of "-0" flags. #39

Open SandorDobos opened 3 years ago

SandorDobos commented 3 years ago

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.)