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

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

本文介绍了错误的IO操作顺序使用putStr和getLine的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码:

  main = do 
putStr测试输入:
内容< - getLine
putStrLn内容

当我运行它时(<$ c $

  asd 
测试输入:asd

为什么测试输入:asd在 asd 之后打印



在,它使用 putStr getLine 的显示输出与我的不同。当我使用 putStrLn 时,程序按预期工作(打印,然后提示并打印)。

ghc 中存在错误,或者它应该工作的方式?

解决方案

这是因为ghci禁用缓冲,而用ghc编译的程序默认有行缓冲。你可以通过运行这个来看到:

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

在ghci中,您会看到 NoBuffering 用runghc你可以得到 LineBuffering 。由于换行符不能在用户输入之后打印,提示符也不会。



通过添加 hFlush stdout (或者使用 hSetBuffering stdout NoBuffering 禁用缓冲,但这可能很糟糕)。


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?

解决方案

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

这篇关于错误的IO操作顺序使用putStr和getLine的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

06-29 00:43