[Issue 4474] Better stdin.byLine()

d-bugmail at puremagic.com d-bugmail at puremagic.com
Sat Jul 17 09:10:51 PDT 2010


http://d.puremagic.com/issues/show_bug.cgi?id=4474



--- Comment #3 from bearophile_hugs at eml.cc 2010-07-17 09:10:49 PDT ---
This is a small test program (dmd v2.047):

import std.string, std.stdio;
void main() {
    int[string] aa;
    foreach (line; stdin.byLine())
        foreach (word; line.split())
            aa[word]++;
    foreach (word, freq; aa)
        writeln(freq, " ", word);
}


Running with itself as input data:
test.exe < test.d


Prints:
1 eln(fr
1 q, " ", wo
1     writeln
1 }
1 "
1 }
1 }
1 writeln
2     wri
1    wri
1  ", word);
))
1 , w
1 q, " ", word);

1 eln(fr
1 q, "
1 freq,
1 ",
1 eln(freq, "
1  writeln(fr
1 word);
1 writeln(freq,
1 fre
1 e


This shows that byLine() is bug-prone (unsafe).


While this program:

import std.string, std.stdio;
void main() {
    int[string] aa;
    foreach (line; stdin.byLine())
        foreach (word; line.split())
            aa[word.dup]++;
    foreach (word, freq; aa)
        writeln(freq, " ", word);
}


Prints a more correct output:

1 (word,
1 std.stdio;
1 int[string]
1 }
1 "
1 void
1 import
3 foreach
1 main()
1 aa)
1 line.split())
1 stdin.byLine())
1 (line;
1 freq;
1 (word;
1 ",
1 std.string,
1 word);
1 writeln(freq,
1 aa[word.dup]++;
1 aa;
1 {


It's easy to forget dupping/idupping.

-- 
Configure issuemail: http://d.puremagic.com/issues/userprefs.cgi?tab=email
------- You are receiving this mail because: -------


More information about the Digitalmars-d-bugs mailing list