【问题标题】:Haskell console program outputs in wrong order [duplicate]Haskell控制台程序输出顺序错误[重复]
【发布时间】:2016-08-13 11:00:43
【问题描述】:

所以我只是做了一个程序,它要求输入一个数字 n 并显示斐波那契数列的第 n 项:

import Control.Monad (forever)

main = forever $ do
    putStrLn ""
    putStr "Which Fibonacci sequence number do you need? "
    number <- readLn :: IO Int
    putStrLn $ "The Fibonacci number you wanted is " ++ (show $ fib number) ++ "."
    putStrLn ""
    where  fib :: Int -> Integer
           fib number = fibs !! number
           fibs = 0 : 1 : zipWith (+) fibs (tail fibs)

当我在 GHCi 或通过 runhaskell 运行程序时,它执行得很好;也就是说,要求我输入一个数字,允许我在同一行输入它并在另一行返回一个数字:

Gallifreian@Gallifrey:~/Haskell$ ghci
GHCi, version 7.10.3: http://www.haskell.org/ghc/  :? for help
Prelude> :l Fib.hs
[1 of 1] Compiling Main             ( Fib.hs, interpreted )
Ok, modules loaded: Main.
*Main> main

Which Fibonacci sequence number do you need? 4
The Fibonacci number you wanted is 3.

但是,当我运行编译后的程序时,它会返回:

Gallifreian@Gallifrey:~/Haskell$ ./Fib

4
Which Fibonacci sequence number do you need? The Fibonacci number you wanted is 3.

我。 e.等待我输入一个数字,然后在一行上返回所有提示。 我做错了什么?有没有办法解决这个问题?

【问题讨论】:

标签: haskell


【解决方案1】:

看起来 stdout 开启了行缓冲,这意味着对 putStr 的调用仅将输出存储在缓冲区中,直到调用 putStrLn 才会输出。您可以使用 putStrLn 作为提示符来修复输出,或禁用标准输出上的缓冲。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-12-12
    • 1970-01-01
    • 2011-09-07
    • 2015-03-04
    • 2021-05-12
    • 1970-01-01
    • 2018-10-18
    • 2013-11-07
    相关资源
    最近更新 更多