views:

156

answers:

1

I have a code :

main = do
    putStr "Test input : "
    content <- getLine
    putStrLn content

And when I run it (with runhaskell) or compile it (ghc 6.10.4) result is like this:

asd
Test input : asd

I'm new to haskell and in my opinion printing should be first. Am I right? In code sample on http://learnyouahaskell.com/ which used putStr then getLine presented output is different than mine (IMHO correct). When I use putStrLn program works as expected (print then prompt and print).

Is it a bug in ghc, or it is the way that it should work?

+14  A: 

This is because ghci disables buffering, while a program compiled with ghc has line buffering by default. You can see this by running this:

import IO
main = print =<< hGetBuffering stdout

In ghci you see NoBuffering while with runghc you get LineBuffering. Since the newline character doesn't print until after the user input, the prompt doesn't either.

Fix it by adding hFlush stdout after your prompt (or disable buffering with hSetBuffering stdout NoBuffering, but that’s probably bad).

jleedev
Thanks! It's good to know. I haven't considered this is because buffering.
QWRp