www.digitalmars.com         C & C++   DMDScript  

digitalmars.D - writef and formatting specs

reply Kevin Bealer <Kevin_member pathlink.com> writes:
I love the writef(".. %s..", object) concept.  But I have a suggestion:

What if the toString() method had a second variant:

:class Object
:{
:    char[] toString();
:    char[] toString(int Flags, int Width, int Precision)
:    {
:        // default to no-parameter version
:        return toString();
:    }
:}

This second variety could be overridden to let the object code customize the
output, based on the flags and widths modifiers.

Taking a hypothetical "class DateTime", you could produce:

"9/30"
"2004-09-30"
"September 30th, 2004. 21:42.0123 EST"

. Automatically compensating for field width.

Also, non-primitive "numerical" types (matrix!(double)?) could format their
contents accordingly, passing down the parameters.

:class IntList {
:    T[] values;
:    char[] toString(int Flags, int Width, int Precision)
:    {
:        char[] output;
:        foreach(...) {
:            foreach(T key; ...)
:                output ~= key.toString(Flags, Width, Precision) ~ ", ";
:            }
:            output ~= "\n"
:        }
:    }
:}

: IntList foo;
: writef("%4.4s", foo);

is like:

: writef("%4.4s, ", foo[0]);
: writef("%4.4s, ", foo[1]);
: ...

I know the Width can already be handled by writef(), but it would be neat to
have Width, so that (for example), word-breaking (not to be confused with
oath-breaking) could be done with certain kinds of text objects. and for
efficiency.

Kevin
Sep 30 2004
parent "Walter" <newshound digitalmars.com> writes:
That's a good idea. -Walter
Oct 01 2004