reading file byLine

Namal via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Thu Sep 3 14:58:58 PDT 2015


On Wednesday, 2 September 2015 at 22:19:11 UTC, wobbles wrote:
> On Wednesday, 2 September 2015 at 21:53:20 UTC, Namal wrote:
>> Thx guys, this helped alot. The next thing I want to do is 
>> read the file line by line and split the stream into words. I 
>> found this example of code that seems to do sort of something 
>> like it. How can I modyfy it so I can store the words in an 
>> array of strings? Is a => a.length the iterator range?
>>
>>
>> import std.algorithm, std.stdio, std.string;
>> // Count words in a file using ranges.
>> void main()
>> {
>>     auto file = File("file.txt"); // Open for reading
>>     const wordCount = file.byLine()            // Read lines
>>                           .map!split           // Split into 
>> words
>>                           .map!(a => a.length) // Count words 
>> per line
>>                           .sum();              // Total word 
>> count
>>     writeln(wordCount);
>> }
>
>
> I would do what you want like this
>
> auto file = File("file.txt");
> auto words = file.byLine()           // you've all lines in  
> range
>                  .map!(a => a.split); // read each line, 
> splitting it into words
>                                      // now you've a range, 
> where each element is an array of words
>
> The map!(a => a.split) line simply maps each element to the 
> return value of a.split - this is the predicate.
>
> The a => a.split syntax is a lambda expression that tells map 
> what to do on each element.

hello, just copy pasting this brought me those errors:


ep18.d(10): Error: no property 'split' for type 'char[]'
/usr/include/dmd/phobos/std/algorithm.d(427):        instantiated 
from here: MapResult!(__lambda1, ByLine!(char, char))
ep18.d(10):        instantiated from here: map!(ByLine!(char, 
char))

and then a long list to the end of my code
  Error: undefined identifier a



More information about the Digitalmars-d-learn mailing list