Wrong IO actions order using putStr and getLine

帅比萌擦擦* 提交于 2019-11-26 07:38:07

问题


I have the following code:

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

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

asd
Test input : asd

Why is Test input : asd being printed after asd?

In the code sample on http://learnyouahaskell.com/, which uses putStr, the getLine\'s presented output is different than mine. When I use putStrLn the program works as expected (print, then prompt, and print).

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


回答1:


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



来源:https://stackoverflow.com/questions/2500459/wrong-io-actions-order-using-putstr-and-getline

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!