sformat

Converts its arguments according to a format string into a buffer. The buffer has to be large enough to hold the formatted string.

The second version of sformat takes the format string as a template argument. In this case, it is checked for consistency at compile-time.

  1. char[] sformat(char[] buf, const(Char)[] fmt, Args args)
  2. char[] sformat(char[] buf, Args args)
    char[]
    sformat
    (
    alias fmt
    Args...
    )
    (
    char[] buf
    ,
    Args args
    )

Parameters

buf char[]

the buffer where the formatted string should go

fmt
args Args

a variadic list of arguments to be formatted

Args

a variadic list of types of the arguments

Return Value

Type: char[]

A slice of buf containing the formatted string.

Throws

A RangeError if buf isn't large enough to hold the formatted string and a FormatException if formatting did not succeed.

Note: In theory this function should be @nogc. But with the current implementation there are some cases where allocations occur:

  • An exception is thrown.
  • A custom toString function of a compound type allocates.

Examples

char[20] buf;
assert(sformat(buf[], "Here are %d %s.", 3, "apples") == "Here are 3 apples.");

assert(buf[].sformat("Increase: %7.2f %%", 17.4285) == "Increase:   17.43 %");

The format string can be checked at compile-time:

char[20] buf;

assert(sformat!"Here are %d %s."(buf[], 3, "apples") == "Here are 3 apples.");

// This line doesn't compile, because 3.14 cannot be formatted with %d:
// writeln(sformat!"Here are %d %s."(buf[], 3.14, "apples"));

Meta