View source code
Display the source code in std/format/write.d from which this page was generated on github.
Report a bug
If you spot a problem with this page, click here to create a Bugzilla issue.
Improve this page
Quickly fork, edit online, and submit a pull request for this page. Requires a signed-in GitHub account. This works well for small changes. If you'd like to make larger changes you may want to consider using local clone.

Function std.format.write.formattedWrite

Converts its arguments according to a format string and writes the result to an output range.

uint formattedWrite(Writer, Char, Args...) (
  auto ref Writer w,
  scope const Char[] fmt,
  Args args
);

uint formattedWrite(alias fmt, Writer, Args...) (
  auto ref Writer w,
  Args args
)
if (isSomeString!(typeof(fmt)));

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

Parameters

NameDescription
w an output range, where the formatted result is written to
fmt a format string
args a variadic list of arguments to be formatted
Writer the type of the writer w
Char character type of fmt
Args a variadic list of types of the arguments

Returns

The index of the last argument that was formatted. If no positional arguments are used, this is the number of arguments that where formatted.

Throws

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. See sformat for more details.

Example

import std.array : appender;

auto writer1 = appender!string();
formattedWrite(writer1, "%s is the ultimate %s.", 42, "answer");
writeln(writer1[]); // "42 is the ultimate answer."

auto writer2 = appender!string();
formattedWrite(writer2, "Increase: %7.2f %%", 17.4285);
writeln(writer2[]); // "Increase:   17.43 %"

Example

The format string can be checked at compile-time:

import std.array : appender;

auto writer = appender!string();
writer.formattedWrite!"%d is the ultimate %s."(42, "answer");
writeln(writer[]); // "42 is the ultimate answer."

// This line doesn't compile, because 3.14 cannot be formatted with %d:
// writer.formattedWrite!"%d is the ultimate %s."(3.14, "answer");

Authors

Walter Bright, Andrei Alexandrescu, and Kenji Hara

License

Boost License 1.0.