Buffered Files & Associative Arrays
Michael
mcoupland at gmail.com
Tue Jan 22 00:35:01 PST 2008
Greetings all!
When I compile and run the below program with a sample input test.txt file, I get some very strange behavior. It behaves like a problem with strange strings coming from a BufferedFile that for some reason the associative array can't handle.
With test.txt containing three one-character lines:
a
b
c
...I get the output:
a 1
b 2 b 2
c 3 c 3 c 3
...rather than the expected:
a 1
a 1 b 2
a 1 b 2 c 3
With test.txt containing longer strings:
first
second
third
...the program crashes entirely with the following output:
first 1
Error: ArrayBoundsError TestArray(15)
However, if I replace the two relevant lines with the following:
string[] file = ["first","second","third"]; // or ["a","b","c"]
foreach( int n, string line; file )
...then the program runs as expected. But what's the difference?? Adding newlines to the string constants above doesn't do any harm, which was what I had first suspected as the culprit.
I don't think I'm missing anything obvious; can someone please confirm I'm not crazy?
Thanks!
Michael
--------------------------------------------------------------
import std.stdio;
import std.stream;
int main( char[][] args )
{
int[string] Ar;
Stream file = new BufferedFile("test.txt");
foreach( ulong n, string line; file )
{
Ar[line] = n;
foreach( string k; Ar.keys )
writef("%s %d ", k, Ar[k] );
writefln("");
}
return 0;
}
More information about the Digitalmars-d
mailing list