[Haskell-beginners] Simple IO problem

Johan Tibell johan.tibell at gmail.com
Thu Mar 4 13:44:00 EST 2010


On Thu, Mar 4, 2010 at 7:30 PM, Brent Yorgey <byorgey at seas.upenn.edu> wrote:

> On Thu, Mar 04, 2010 at 01:06:42PM -0500, Ali Razavi wrote:
> > Why doesn't this work the way it's supposed to, or the way it's
> intuitively
> > apparent from the code, that is, showing the prompt first, getting the
> line
> > next, and printing the result finally?
> >
> > main = do
> >         putStr "Please Enter Your Name: "
> >         name <- getLine
> >         putStrLn ("Hello " ++ name)
> >
> >
> > changing putStr with putStrLn rectifies it to the expected behavior, but
> I
> > wonder why this version misbehaves. FWIW, I use ghc in cygwin.
> >
> > Ali
>
> This is because of output buffering.  By default, LineBuffering is
> used, which means that the runtime will collect output in a buffer
> until seeing a newline, at which point it will actually print the
> buffer contents on the screen.  This is why changing the putStr to
> putStrLn makes it work.  You can turn off output buffering like so:
>
>  import System.IO
>
>  main = do hSetBuffering stdout NoBuffering
>             putStr "Please Enter Your Name: "
>             ... etc.


If you don't want a newline after the prompt you can use `hFlush stdout` to
manually flush the buffer.

Cheers,
Johan
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://www.haskell.org/pipermail/beginners/attachments/20100304/a34c828d/attachment.html


More information about the Beginners mailing list