byLine(n)?
helxi via Digitalmars-d-learn
digitalmars-d-learn at puremagic.com
Sun Jun 11 05:44:05 PDT 2017
On Sunday, 11 June 2017 at 06:28:18 UTC, Stanislav Blinov wrote:
> On Sunday, 11 June 2017 at 05:36:08 UTC, helxi wrote:
>> I was writing a program that reads and prints the first nth
>> lines to the stdout:
>>
>> import std.stdio;
>>
>> void main(string[] args)
>> {
>> import std.algorithm, std.range;
>> import std.conv;
>> stdin.byLine.take(args[1].to!ulong).each!writeln;
>> }
>>
>> As far as I understand the stdin.byLine.take(args[1].to!ulong)
>> part reads all the lines written in stdin.
>> What if I want to make byLine read only and only first nth
>> line?
>>
>> stdin.byLine(args[1].to!ulong).each!writeln;
>>
>> Obviously the code above won't work. Is there any efficient
>> workaround?
>
> You need only the nth line? Then you'd need to `drop` the
> preceding ones:
>
> void main(string[] args) {
> import std.algorithm, std.range, std.stdio, std.conv;
> stdin.byLine.drop(args[1].to!int-1).front.writeln;
> }
>
> Or if you need every nth line, combine `drop` and `stride`:
>
> void main(string[] args) {
> import std.algorithm, std.range, std.stdio, std.conv;
> auto step = args[1].to!int;
> stdin.byLine.drop(step-1).stride(step).each!writeln;
> }
I was actually just looking for ways to read the first n line and
then print it ($man head). My current program
1. reads all the lines provided by the stdin (bottleneck)
2. takes the first n lines (bottleneck)
3. prints each line
I want to
1. read all the lines
2. when line number n is reached, stop reading the rest of the
input
3. print each line
More information about the Digitalmars-d-learn
mailing list