Big Oversight with readln?

Jonathan Marler via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Thu Feb 23 18:43:38 PST 2017


I can't figure out how to make use of the full capacity of 
buffers that are allocated by readln.  Take the example code from 
the documentation:

     // Read lines from $(D stdin) and count words

     void main()
     {
         char[] buf;
         size_t words = 0;

         while (!stdin.eof)
         {
             char[] line = buf;
             stdin.readln(line);
             if (line.length > buf.length)
                 buf = line;

             words += line.split.length;
         }

         writeln(words);
     }

When buf is not large enough to hold the line, readln will 
allocate a new buffer to accomodate and this example shows how 
you can save that new buffer to reuse the next time.  The problem 
is that the capacity of the new buffer is nowhere to be found. 
readln only returns the line that was read which is only a slice 
of the buffer that was allocated.  The next time that readln is 
called, it will not read past the slice even if the capacity of 
the buffer it allocated was larger.  This will cause a new 
allocation/copy every time you read a line that was larger than 
all the previous lines, even if a previous allocation was already 
large enough. This seems like a big oversight to me, I must be 
missing something right?


More information about the Digitalmars-d-learn mailing list