
I encountered the following issue last night. Writing a program like this: main = do putStr "> " x <- getLine putStr x behaves as expected in hugs and ghci (first prints "> ", then waits for input, then prints the input). However, when compiling and running an executable via ghc, the behavior was very different. I saw a blank console screen and when I typed something it was echoed back to me (as in "> 25") only after I hit enter. This is trivially fixed by flushing: main = do putStr "> " hFlush stdout x <- getLine putStr x or by turning off buffering. Is this the intended behavior? This problem does not appear when using putStrLn (as it flushes automatically) and is quite distracting to newbies. To me it looks like this behavior is at odds with something one can reasonably expect and bufferring should be turned off by default. What do you guys think? Thanks, - Slava.

Vyacheslav Akhmechet wrote:
I encountered the following issue last night. Writing a program like this:
main = do putStr "> " x <- getLine putStr x
behaves as expected in hugs and ghci (first prints "> ", then waits for input, then prints the input). However, when compiling and running an executable via ghc, the behavior was very different. I saw a blank console screen and when I typed something it was echoed back to me (as in "> 25") only after I hit enter. This is trivially fixed by flushing:
main = do putStr "> " hFlush stdout x <- getLine putStr x
or by turning off buffering. Is this the intended behavior?
Yes, it's the intended behaviour.
This problem does not appear when using putStrLn (as it flushes automatically) and is quite distracting to newbies. To me it looks like this behavior is at odds with something one can reasonably expect and bufferring should be turned off by default. What do you guys think?
We did at one time have some code that flushed stdout before reading from stdin, but I wasn't too keen on the idea so I didn't implement that idea in the current version of the IO library. Personally I think the current behaviour is ok, despite the fact that it does trip people up occasionally. If you think about it, it's consistent: stdout is line bufferred, so it doesn't get flushed until you output a \n. Cheers, Simon
participants (2)
-
Simon Marlow
-
Vyacheslav Akhmechet