Wrong IO actions order using putStr and getLine

后端 未结 1 638
暗喜
暗喜 2020-11-27 17:41

I have the following code:

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

When I run it (with

相关标签:
1条回答
  • 2020-11-27 18:21

    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 System.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).

    0 讨论(0)
提交回复
热议问题