Calling readln() after readf

Ali Çehreli acehreli at yahoo.com
Mon Jun 20 00:43:17 UTC 2022


On 6/19/22 15:52, Gary Chike wrote:
 > On Saturday, 24 April 2021 at 22:13:45 UTC, Ali Çehreli wrote:
 >> On 4/24/21 7:46 AM, PinDPlugga wrote:
 >> ...
 >> As a general solution, you can use a function like this:
 >>
 >> auto readLine(S = string)(File file = stdin) {
 >>   while (!file.eof) {
 >>     auto line = file.readln!S.strip;
 >>     if (!line.empty) {
 >>       return line;
 >>     }
 >>   }
 >>
 >>   return null;
 >> }
 >>
 >> Ali
 >
 > Hi Ali,
 >
 > Being a new D learner, I've noticed this behavior as well. Thank you for
 > providing the 'readLine' function! Would it be considered poor coding
 > style to intercept the stream between readf and readln with the
 > following statement?  :
 >
 > ```d
 >       auto catcher = readln.strip;
 > ```

The original program said "Please enter a number: ". If the program was 
interacting with a human and the human entered a number, then the rest 
of the line would be understood to be ignored and your method works.

On the other hand, the readLine() function would not ignore the rest of 
the line and use it.

But I think yours makes more sense. :)

But when the program interacts with piped data, there may be multiple \n 
characters and all of those might have to be ignored before reading the 
next non-empty line. So you may want to do readln.strip multiple times? 
I don't know. It all depends on the use case.

 > P.S. I love your book on D! :)

Thank you! :)

 >
 > Cheers,
 >
 > Gary Chike
 >

Ali



More information about the Digitalmars-d-learn mailing list