www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - how to get line number after readln

reply "Robert Hathaway" <robert.of.santiago gmail.com> writes:
I've got a program that reads a text file line by line (using 
std.stdio readln()) and I'd like to refer to the line number when 
I send a message to stderr upon finding a mis-formatted line.  Is 
there a way to get the current line number?  Of course, I could 
create a counter and increment it with each call to readln, but 
is there a "cool" way of doing this?

Okay, call me lazy... just don't call me late for dinner! :-)

Robert
Jun 04 2014
parent reply =?UTF-8?B?QWxpIMOHZWhyZWxp?= <acehreli yahoo.com> writes:
On 06/04/2014 05:05 PM, Robert Hathaway wrote:
 I've got a program that reads a text file line by line (using std.stdio
 readln())
Consider using byLine() instead. (Important: byLine uses an internal buffer for the line; so, don't forget to make a copy if you want to store the line for later use.)
 and I'd like to refer to the line number when I send a message
 to stderr upon finding a mis-formatted line.  Is there a way to get the
 current line number?  Of course, I could create a counter and increment
 it with each call to readln, but is there a "cool" way of doing this?

 Okay, call me lazy... just don't call me late for dinner! :-)

 Robert
One cool way is a zipped sequence: import std.stdio; import std.range; void main() { foreach (i, line; zip(sequence!"n", File("deneme.txt").byLine)) { writefln("%s: %s", i, line); } } Ali
Jun 04 2014
parent "Brad Anderson" <eco gnuk.net> writes:
On Thursday, 5 June 2014 at 00:33:26 UTC, Ali Çehreli wrote:
 On 06/04/2014 05:05 PM, Robert Hathaway wrote:
 I've got a program that reads a text file line by line (using 
 std.stdio
 readln())
Consider using byLine() instead. (Important: byLine uses an internal buffer for the line; so, don't forget to make a copy if you want to store the line for later use.)
 and I'd like to refer to the line number when I send a message
 to stderr upon finding a mis-formatted line.  Is there a way 
 to get the
 current line number?  Of course, I could create a counter and 
 increment
 it with each call to readln, but is there a "cool" way of 
 doing this?

 Okay, call me lazy... just don't call me late for dinner! :-)

 Robert
One cool way is a zipped sequence: import std.stdio; import std.range; void main() { foreach (i, line; zip(sequence!"n", File("deneme.txt").byLine)) { writefln("%s: %s", i, line); } } Ali
Once this[1] gets merged you'll be able to do this: foreach (lineNum, line; File("deneme.txt").byLine().enumerate(1)) writefln("%s: %s", lineNum, line); Which is a bit more clear about the intent. 1. https://github.com/D-Programming-Language/phobos/pull/1866
Jun 04 2014