Search code examples
cvariadic-functions

How to get a leading zero?


I'm coding my own version of printf as an exercise but I'm having a very hard time figuring out how to get the 0 flag. It would probably be trivial if it was at all times leading a number but the exercise specifically says:

"Manage any combination of the following flags: ’-0.’ and the field minimum width under all conversions."

My approach to '-' '#' and other flags was just to memchr them to see if they were present but this doesn't work with 0 as it can be present in width or precision is there a LibC function that allows me to do this? What course of action would you take in order to tackle this problem?


Solution

  • Rather than checking if a format specification character is present in the entire format string, you would be better off processing it character by character (in sequence) and acting on each as it "arrives".

    Each format specifier character can be read by a state machine and just store its effect. Once you hit a character that ends a format specifier (like d or s), you grab an argument from the variable argument list and use those stored effects to modify the output.

    Then clear the effects and start on the next specifier.