Help with Associative array problems.

Spacen Jasset spacenjasset at yahoo.co.uk
Wed Apr 2 04:23:54 PDT 2008


Frits van Bommel wrote:
> 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".
I see ok. This is all very subtle though. Is my solution adding a .dup 
the best way or can I do something else?


More information about the Digitalmars-d-learn mailing list