Help with Associative array problems.
Frits van Bommel
fvbommel at REMwOVExCAPSs.nl
Wed Apr 2 04:04:34 PDT 2008
Spacen Jasset wrote:
> The program below does not print what it should, either using a File or
> the TArrayStream.
>
> It prints this:
>
> user at vm-fruitbat:~$ dmd t.d
> user at vm-fruitbat:~$ ./t
> Error: 4invalid UTF-8 sequence
> Material user at vm-fruitbat:~$
>
[snip]
> foreach(ulong line_no, ref string line; file) {
> string words[] = line.split();
> m[words[1]] = 1;
> }
> foreach (char[] k, ref int v; m) {
> writefln("Material %s", k);
> }
> }
File.opApply (which is called by foreach), as implemented in superclass
Stream, re-uses a (stack-allocated) buffer for each iteration. This is
more efficient, but means the string put into the loop variable is only
valid for that iteration; if you want to keep it beyond that you need to
allocate a copy.
This is mentioned in the documentation for InputStream[1]: "The string
passed in line may be reused between calls to the delegate."
[1] <http://www.digitalmars.com/d/1.0/phobos/std_stream.html>, search
for "opApply".
More information about the Digitalmars-d-learn
mailing list