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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With