使用putStr在错误的时刻打印邮件 [英] Messages printed at the wrong moment with putStr

查看:113
本文介绍了使用putStr在错误的时刻打印邮件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  import Control.Monad 
import Data.Char

main = forever $ do
putStr给我一些输入:
l < - getLine
putStrLn $ map toUpper l

我一直在学习Haskell从学习你haskell。当我尝试运行这段代码时,它的行为并不像它应该那样。

  l 
给我一些输入:L
abc
给我一些输入:ABC

当我运行它时,它不会先不打印字符串,我可以输入。在提供了一些输入之后,在这种情况下 l 它会像这样返回我:给我一些输入:L p>

它应该做的是,通过打印给我一些输入:,并且在输入它后应该返回输入大写。



我该如何解决这个问题?

解决方案

正如 Michail 指出的那样,这是一个缓冲问题,可以通过 hSetBuffering for stdout

  import Control.Monad 
import Data.Char
import System.IO

main = do
hSetBuffering stdout NoBuffering
永远$ do
putStr给我一些输入:
l < - getLine
putStrLn $ map toUpper l

如果f或任何你不想改变的原因缓冲模式,您可以使用 hFlush 可以在需要的地方额外刷新缓冲区:

  import Control.Monad 
import Data.Char
import System.IO

main = do
永远$ do
putStr给我一些输入:
hFlush stdout
l < - getLine
putStrLn $ map toUpper l


import Control.Monad
import Data.Char

main = forever $ do
    putStr "Give me some input: "
    l <- getLine
    putStrLn $ map toUpper l

I have been learning Haskell from learn you haskell. When i try to run this code it does not behave like it should.

l
Give me some input: L
abc
Give me some input: ABC

When i run this it doesn't print the string first and i can input. After providing some input, in this case l it returns me like this : Give me some input: L.

What it should do is, ask for input by printing Give me some input: and after putting the input it shall return the input in uppercase.

How can i fix this?

解决方案

As Michail points out, it is a buffering issue, which can be solved with hSetBuffering for stdout:

import Control.Monad
import Data.Char
import System.IO

main = do
    hSetBuffering stdout NoBuffering
    forever $ do
    putStr "Give me some input: "
    l <- getLine
    putStrLn $ map toUpper l

If for whatever reason you don't want to change the buffer mode for the whole program, you can use hFlush to do an extra flushing of the buffer exactly where you need it:

import Control.Monad
import Data.Char
import System.IO

main = do
    forever $ do
    putStr "Give me some input: "
    hFlush stdout
    l <- getLine
    putStrLn $ map toUpper l

这篇关于使用putStr在错误的时刻打印邮件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆