www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - readf interferes with readln

reply Bastiaan Veelo <Bastiaan Veelo.net> writes:
Hi,

I am having trouble explaining the following to someone learning 
D. Can someone explain why readln has different behaviour when it 
is preceded by readf?

Suppose we want to not end the program before the user presses 
Enter by having readln at the end of main():

```
import std.stdio;

void main()
{
     int num;
     write("Give a number ");
     readf(" %s", num);
     writeln("Thanks");
     readln;
     readln;
}
```

In this example this requires twice readln. When you comment out 
readf, you need readln only once.

Thanks!
Apr 27 2017
parent reply ketmar <ketmar ketmar.no-ip.org> writes:
Bastiaan Veelo wrote:

 Hi,

 I am having trouble explaining the following to someone learning D. Can 
 someone explain why readln has different behaviour when it is preceded by 
 readf?

 Suppose we want to not end the program before the user presses Enter by 
 having readln at the end of main():

 ```
 import std.stdio;

 void main()
 {
      int num;
      write("Give a number ");
      readf(" %s", num);
      writeln("Thanks");
      readln;
      readln;
 }
 ```

 In this example this requires twice readln. When you comment out readf, 
 you need readln only once.

 Thanks!
'cause your `readf()` stops before consuming `'\n`. i.e. EOL is still in input buffer, and first `readln()` will immediately consume it.
Apr 27 2017
parent Bastiaan Veelo <Bastiaan Veelo.net> writes:
On Thursday, 27 April 2017 at 08:37:26 UTC, ketmar wrote:
 Bastiaan Veelo wrote:

 Hi,

 I am having trouble explaining the following to someone 
 learning D. Can someone explain why readln has different 
 behaviour when it is preceded by readf?

 Suppose we want to not end the program before the user presses 
 Enter by having readln at the end of main():

 ```
 import std.stdio;

 void main()
 {
      int num;
      write("Give a number ");
      readf(" %s", num);
      writeln("Thanks");
      readln;
      readln;
 }
 ```

 In this example this requires twice readln. When you comment 
 out readf, you need readln only once.

 Thanks!
'cause your `readf()` stops before consuming `'\n`. i.e. EOL is still in input buffer, and first `readln()` will immediately consume it.
Right, of course. Thanks a lot.
Apr 27 2017