Dlang byLineCopy skips rows

I have the following program D, which should group the input lines in the size of 3 groups.

import std.stdio;
import std.range;
import std.array;

void main()
{
  while (!stdin.eof) {
    auto currentBlock = array(take(stdin.byLineCopy, 3));

    foreach (i, e; currentBlock) {
      writefln("%d) %s", i, e);
    }
  }
}

and taking into account the following input

Mercury
Venus
Earth
Mars
Jupiter
Saturn
Uranus
Neptune
Pluto

it outputs the result.

0) Mercury
1) Venus
2) Earth
0) Jupiter
1) Saturn
2) Uranus
0) Pluto

skipping the line at the border on every iteration (Mars and Neptune are not displayed). What am I doing wrong?

+6
source share
2 answers

stdin.byLineCopy calls popFront , which means that repeated calls of the same input stream will pass elements. Try to create a range of byLineCopyonly once at the beginning:

void main()
{
    auto r = stdin.byLineCopy;
    while (!r.empty) {
        foreach (i, e; r.take(3).enumerate) {
          writefln("%d) %s", i, e);
        }
    }
}

You do not need to check eof, as you byLineCopymust handle this.

+4
source

It looks like you want to std.range.chunks, in conjunction with std.range.enumerate, to keep the indexes:

void main()
{
    foreach (i, chunk; stdin.byLineCopy.array.chunks(3).enumerate) {
      writefln("%s", chunk);
    }
}

Note that .arrayrequired, as chunksrequired ForwardRange, and stdin.byLineCopy- InputRange.

+1
source

Source: https://habr.com/ru/post/1016732/


All Articles