2

So I just made a program that asks for a number n and displays n th term of the Fibonacci sequence:

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)

When I run the program in GHCi or through runhaskell, it executes fine; that is, asks me for a number, allows me to enter it on the same line and returns a number on another line:

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.

However, when I run the compiled program, it returns this:

Gallifreian@Gallifrey:~/Haskell$ ./Fib

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

I. e. waits for me to enter a number and then returns all prompts on one line. What have I done wrong? Is there a way around this?

Benjamin Hodgson
  • 42,952
  • 15
  • 108
  • 157
Gallifreyan
  • 232
  • 4
  • 11
  • 2
    Found answer, see http://stackoverflow.com/questions/2500459/wrong-io-actions-order-using-putstr-and-getline (I don't have any flags left to mark this as duplicate) – Markus Laire Aug 13 '16 at 11:16
  • Related: https://stackoverflow.com/questions/13190314/haskell-do-monad-io-happens-out-of-order – Gallifreyan Feb 19 '17 at 18:15

1 Answers1

1

It looks like stdout has line buffering on, which means that the calls to putStr are only storing the output in a buffer, which is not being output until putStrLn is called. You can fix your output by using putStrLn for your prompt, or disabling buffering on stdout.

user1937198
  • 4,987
  • 4
  • 20
  • 31