Calling readln() after readf

Ali Çehreli acehreli at yahoo.com
Sat Apr 24 22:13:45 UTC 2021


On 4/24/21 7:46 AM, PinDPlugga wrote:

 >      write("Please enter a number: ");
 >      double number;
 >      readf(" %s", number);

Just to make sure, this is a common issue for other languages as well.

As the explanation, the character ('\n') that you injected into stdin by 
pressing Enter is not (and should not be) removed by readf.

 >      write("Please enter a string: ");
 >      string input = strip(readln());

Because of that '\n' character, that readln() reads an empty line. There 
is no way other than reading and discarding all input at stdin but 
luckily, readf's "formatted" behavior is able to take care of it because 
any character that match the format string will be read and discarded by 
readf:

   readf(" %s\n", number);

As a side note, that '\n' should work on all platforms even if the 
terminal injects two characters.

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



More information about the Digitalmars-d-learn mailing list