View source code
Display the source code in std/format/read.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.read.formattedRead

Reads an input range according to a format string and stores the read values into its arguments.

uint formattedRead(Range, Char, Args...) (
  auto ref Range r,
  const(Char)[] fmt,
  auto ref Args args
);

uint formattedRead(alias fmt, Range, Args...) (
  auto ref Range r,
  auto ref Args args
)
if (isSomeString!(typeof(fmt)));

Format specifiers with format character 'd', 'u' and 'c' can take a '*' parameter for skipping values.

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

Parameters

NameDescription
r an input range, where the formatted input is read from
fmt a format string
args a variadic list of arguments where the read values are stored
Range the type of the input range r
Char the character type used for fmt
Args a variadic list of types of the arguments

Returns

The number of variables filled. If the input range r ends early, this number will be less than the number of variables provided.

Throws

A FormatException if reading did not succeed.

Note

For backward compatibility the arguments args can be given as pointers to that variable, but it is not recommended to do so, because this option might be removed in the future.

Example

string object;
char cmp;
int value;

writeln(formattedRead("angle < 36", "%s %c %d", object, cmp, value)); // 3
writeln(object); // "angle"
writeln(cmp); // '<'
writeln(value); // 36

// reading may end early:
writeln(formattedRead("length >", "%s %c %d", object, cmp, value)); // 2
writeln(object); // "length"
writeln(cmp); // '>'
// value is not changed:
writeln(value); // 36

Example

The format string can be checked at compile-time:

string a;
int b;
double c;

writeln("hello!124:34.5".formattedRead!"%s!%s:%s"(a, b, c)); // 3
writeln(a); // "hello"
writeln(b); // 124
writeln(c); // 34.5

Example

Skipping values

string item;
double amount;

writeln("orange: (12%) 15.25".formattedRead("%s: (%*d%%) %f", item, amount)); // 2
writeln(item); // "orange"
writeln(amount); // 15.25

// can also be used with tuples
import std.typecons : Tuple;

Tuple!(int, float) t;
char[] line = "1 7643 2.125".dup;
formattedRead(line, "%s %*u %s", t);
assert(t[0] == 1 && t[1] == 2.125);

Authors

Walter Bright, Andrei Alexandrescu, and Kenji Hara

License

Boost License 1.0.