Associative Array - where's my error?
Adrian Mercieca
amercieca at gmail.com
Wed Apr 27 21:22:03 PDT 2011
Hi,
I am currently learning D, but have ran into a problem.
I wrote this simple program:
import std.stdio;
import std.string;
import std.conv;
void main()
{
int[string] dataMap;
foreach(line; stdin.byLine() ) {
auto s = line.split("\t");
auto anum = to!int(s[0]);
auto aname = cast(string)s[1];
dataMap[aname] = anum;
}
foreach(s; dataMap.keys.sort) {
writeln(s);
}
}
The code is in a file named 'rl.d'.
I am running this on Linux (Linux 2.6.32-31-generic-pae #61-Ubuntu SMP i686
GNU/Linux)
The compiler flags used are: dmd -w -wi -O -inline -noboundscheck -release
rl.d.
I invoke the program from the command line with this command:
cat data.txt | ./rl
Basically, this is piping the contents of the data.txt file (below) into
the program.
data.txt contents:
1 ABC
2 DEF
3 GHI
4 JKL
5 MNO
6 PQR
7 STU
8 VWX
9 YZ
There are two 'fields' per line, a number and a string separated by a tab.
Now, when I run the program, I get this output:
YZ
YZ
YZ
YZ
YZ
YZ
YZ
YZ
YZ
Which is nowhere close to what I was expecting.
The program is supposed to read the input line by line, split each line on
tab character and populate an associative array with the key being the 2nd
string value and set the corresponding value to the value of the 1st
field. Then it goes into a loop printing out the sorted keys of the
associative array.
I was expecting output like:
ABC
DEF
GHI
JKL
MNO
PQR
STU
VWX
YZ
but, as shown, I get something completely different and unexpected.
Can anyone shed any light on this for me please? What am I doing wrong?
Thanks.
- Adrian.
More information about the Digitalmars-d-learn
mailing list