format a string like sprintf?

Vijay Nayar madric at gmail.com
Tue Aug 16 09:30:59 PDT 2011


On Tue, 16 Aug 2011 13:23:26 +0000, teo wrote:

> What is the correct way in D to format a string like sprintf? I need to
> pad a number with zeroes. I tried to use std.format.format and
> std.string.format, but had some strange results.

You can go ahead and use the normal std.format to accomplish this task.  
This particular implementation is not very efficient, due to the 
immutable nature of strings, and the fact that I'm adding one character 
at a time.

If you do this operation a lot, you might want to make a version that 
works with pointers instead.


import std.stdio;
import std.format;

void sprintf(ref string s, ...) {
    void putc(dchar c) {
        s ~= c;
    }
    std.format.doFormat(&putc, _arguments, _argptr);
}

void main() {
    string testString;
    // Remember the format string:
    //   % - begins format
    //   0 - use leading '0's
    //   6 - we want 6 total chars printed (includes one for decimal)
    //   . - indicate precision (numbers after decimal)
    //   2 - do not show anything less than 1 cent
    sprintf(testString, "Your change %s is $%06.2f.", "Bob", 12.3456);
    // Output:  "Your change Bob is $012.35."
    writeln(testString);
}


More information about the Digitalmars-d-learn mailing list