2

I'm currently writing a basic console application in Haskell, and I wanted to make it obvious to the user when they're being asked for input by putting > at the beginning of the line. Sounds simple enough, right?

Consider this bit of code:

main :: IO ()
main = do
    putStr "\nSay something:\n> "
    input <- getLine
    putStrLn ("You said " ++ input)

This works perfectly as intended when executed in ghci, however when I compile and run the program, now this happens:

Say something:
something
> You said something

Can someone please explain to me how and why this difference in behavior arises, and how I should go about achieving the result I have in mind?

Axim
  • 332
  • 3
  • 11
  • @JohnE. I'm sorry but you're gonna have to elaborate on that. – Axim Dec 15 '15 at 20:46
  • 2
    Try flushing stdout after your putStr. (I think turning off buffering is, when applied generally, a bad idea.) – hao Dec 15 '15 at 20:48

1 Answers1

4

That is due to buffering, you may turn it off by:

import System.IO (stdout, hSetBuffering, BufferMode(NoBuffering))

main :: IO ()
main = do
    hSetBuffering stdout NoBuffering
    -- rest of the code

or alternatively do hFlush stdout when you need to flush the io stream.

behzad.nouri
  • 74,723
  • 18
  • 126
  • 124