2

When I want to put some text before reading an input in Haskell, I tried writing it like this:

putStr "enter value: "
var <- getLine

However the output requires the user input before it displays the text:

[input]
enter value: 

When I use putStrLn instead of putStr, it displays as it should:

enter value: 
[input]

Why do these two statements function differently? Is it the addition of the newline?

Daniel
  • 509
  • 1
  • 4
  • 17

1 Answers1

11

putStr "enter value: " actually writes to an output buffer, which is flushed to the actual standard output only later on, when the buffer becomes full or when a newline is found.

This is roughly the same mechanism found in the C programming language.

So, even if putStr "enter value: " is run before getLine, we don't see the output message, yet, which feels wrong.

The solution is to flush the standard output handle explicitly.

import System.IO
-- ...
putStr "enter value: "
hFlush stdout
var <- getLine
chi
  • 111,837
  • 3
  • 133
  • 218