Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dlang byLineCopy skipping lines

Tags:

d

I have the following D program that is supposed to group input lines into groups of size 3.

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 given the following input

Mercury
Venus
Earth
Mars
Jupiter
Saturn
Uranus
Neptune
Pluto

it produces the output.

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

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

like image 445
Balagopal Komarath Avatar asked Apr 24 '17 15:04

Balagopal Komarath


1 Answers

stdin.byLineCopy calls popFront, meaning that repeated calls to this on the same input stream will 'skip' elements. Try creating a byLineCopy range only once at the start:

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

You don't need to check for eof, as byLineCopy should handle that.

like image 116
rcorre Avatar answered Oct 16 '22 04:10

rcorre