The OpenD Programming Language

formattedRead

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

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.

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

Parameters

r Range

an input range, where the formatted input is read from

fmt const(Char)[]
args 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

Return Value

Type: uint

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.

Examples

string object;
char cmp;
int value;

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

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

The format string can be checked at compile-time:

string a;
int b;
double c;

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

Skipping values

string item;
double amount;

assert("orange: (12%) 15.25".formattedRead("%s: (%*d%%) %f", item, amount) == 2);
assert(item == "orange");
assert(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);

Meta