使用 putStr 和 getLine 的 IO 操作顺序错误

发布于 2024-08-26 09:27:30 字数 538 浏览 3 评论 0原文

我有以下代码:

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

当我运行它(使用 runhaskell)或编译它(ghc 6.10.4)时,结果如下:

asd
Test input : asd

为什么 Test input : asd 是在 asd 之后打印?

http://learnyouahaskell.com/ 上使用 putStr 的代码示例中, getLine 呈现的输出与我的不同。当我使用 putStrLn 时,程序按预期工作(打印,然后提示,然后打印)。

这是 ghc 中的错误,还是它应该工作的方式?

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

匿名的好友 2024-09-02 09:27:30

这是因为 ghci 禁用了缓冲,而使用 ghc 编译的程序默认具有行缓冲。您可以通过运行以下命令看到这一点:

import System.IO
main = print =<< hGetBuffering stdout

在 ghci 中,您会看到 NoBuffering,而在 runghc 中,您会看到 LineBuffering。由于换行符只有在用户输入之后才会打印,因此提示也不会打印。

通过在提示后添加 hFlush stdout 来修复它(或者使用 hSetBuffering stdout NoBuffering 禁用缓冲,但这可能很糟糕)。

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文