How to make a formatted string ?

Lars T. Kyllingstad public at kyllingen.NOSPAMnet
Wed Mar 17 06:08:28 PDT 2010


Gabriel Laskar wrote:
> Hi,
> 
> I am searching how to do a formatted string like with sprintf()
> 
> I have found std.format.formattedWrite() but when I try :
> 
> Appender!(string) msg;
> formattedWrite(msg, "toto: %0", 42);
> writeln(msg);
> 
> It fails with :
> core.exception.RangeError@�(1582): Range violation
> 
> I have also found std.string.format, but it seems to fail also.

There are two problems here:

   1. Your format specification is wrong.  %0 is not a valid specifier.
   2. msg isn't a string, it's an Appender.  Extract its contents with
      Appender.data instead.

Here's one example of how to do it:

   Appender!string msg;
   formattedWrite(msg, "toto: %s", 42);
   write(msg.data);

If you meant to use positional parameters, then the first parameter is 
number 1, not 0, and you also need a format specifier.  The syntax is then

   formattedWrite(msg, "toto: %1$s", 42);

(This is the POSIX syntax, check out 
http://opengroup.org/onlinepubs/009695399/functions/printf.html for the 
full specification.)

-Lars


More information about the Digitalmars-d-learn mailing list