1

I'm trying to learn d so I started with hello world, and tried to expand a little on it.

import std.stdio;
import core.thread;

void main(string[] args){
    writeln("Hello World!");
    Thread.sleep(dur!("seconds")(5));
    writeln("Press enter key to exit...");
    writeln(readln());
}

so I expect my output to be the following

Hello World!
Press enter key to exit...
//input "abcd"
abcd

but instead I get this

//input "abcd"
Hello World!
Press enter key to exit....
abcd

the sleep function even gets skipped. What is happening?

Max Alibaev
  • 681
  • 7
  • 17
blipman17
  • 523
  • 3
  • 23

1 Answers1

6

This is a FAQ, when I read the title, I expected to see an IDE and you tagged it, so yay! I can't find my old answer to link to, but the short of it is the output and sleep DO happen, they are just buffered by the IDE pipe and not seen until the end.

If you add a stdout.flush(); right before the readln and/or right after the first writeln you'll see output - that forces the buffer to go to screen before doing anything else.

Normal console output will automatically flush on a line, but IDEs are seen as a pipe; the program talking to another program instead of to a user, so it thinks it can buffer by data block instead of by user-visible line.

Adam D. Ruppe
  • 25,382
  • 4
  • 41
  • 60
  • I thought I was going nuts. I expected it not to be a buffer since it's called *writeln()* (when you're using this function you clearly want to write a single line.) I don't know how I could miss this one. – blipman17 Aug 26 '16 at 12:27
  • Yeah, we have considered putting flush in the writeln call, but the buffering gives a big performance boost when talking to pipes or other files normally, so it is doing the right thing in most cases... it just gets confused because IDEs don't look like what they are to the library. – Adam D. Ruppe Aug 26 '16 at 12:34
  • I presume the proposal to make two different versions of `writeln` with and without a built in flush has come around. If I may ask, what was the reason to not do that and do this instead? – blipman17 Aug 26 '16 at 13:29
  • Well, the one there has a built in flush, it just isn't being called because it doesn't realize the ide needs it... but since this is pretty simple to fix and only happens inside the IDE, I don't think the devs are terribly concerned. That said, they might be willing to do it, I don't remember what was said last time. – Adam D. Ruppe Aug 26 '16 at 17:38