6

Let's say we have a short haskell programm:

main = do putStr "2 + 2 = "
          x <- readLn
          if x == 4
             then putStrLn "Correct"
             else putStrLn "Wrong"

What output does it produce?

4

2 + 2 = Correct

Now let's have another:

main = do putStrLn "2 + 2 = "
          x <- readLn
          if x == 4
             then putStrLn "Correct"
             else putStrLn "Wrong"

That produces

2 + 2 =

4

Correct

Where the bold 4 is user-inputted.

Could anybody familiar with Haskell explain to me why that is? And how do I get the desired result, which is

2 + 2 = 4

Correct

Gilles 'SO- stop being evil'
  • 104,111
  • 38
  • 209
  • 254
User1291
  • 7,664
  • 8
  • 51
  • 108

1 Answers1

14

Line buffering. The output buffer is not "flushed" until a complete line of text is written.

Two solutions:

  1. Manually flush the buffer. (putStr followed by hFlush stdout.)
  2. Turn off buffering. (hSetBuffering stdout NoBuffering.)
MathematicalOrchid
  • 61,854
  • 19
  • 123
  • 220