splitting numbers from a test file

bearophile bearophileHUGS at lycos.com
Tue Sep 18 19:59:33 PDT 2012


Craig Dillabaugh:

> 8    auto f = std.stdio.File("test.txt", "r");
> 9    foreach( char[] s; f.byLine() ) {
> 10     string line = std.string.strip( to!string(s) );
> 11     auto parts = std.array.splitter( line );
> 12     writeln("There are ", parts.length, " numbers in line ",
> line_count++);
> 13     foreach(string p; parts) {
> 14     numbers_read ~= to!real(p);
> 15      }
> 16    }
> 17    f.close();
> 18    return 0;
> 19 }
>
> When I try to compile this I get an error:
> test.d(12): Error undefined identifier 'length;

Here to!string() is probably unnecessary, it's a wasted 
allocation.

splitter() returns a lazy range that doesn't know its length.

To solve your problem there are two main solutions: to use 
split() instead of splitter(), or to use walkLength() on the 
range given by splitter().

In theory splitter() should faster, but in practice this isn't 
always true.

Keep in mind that "real" is usually more than 64 bits long, and 
it's not so fast.

Maybe nowdays there are other ways to load that data, I don't 
know if readfln("%(%f %)%") or something similar works.

Bye,
bearophile


More information about the Digitalmars-d-learn mailing list