<div class="gmail_quote">On Thu, Mar 4, 2010 at 7:30 PM, Brent Yorgey <span dir="ltr"><<a href="mailto:byorgey@seas.upenn.edu">byorgey@seas.upenn.edu</a>></span> wrote:<br><blockquote class="gmail_quote" style="margin:0 0 0 .8ex;border-left:1px #ccc solid;padding-left:1ex;">
<div><div></div><div class="h5">On Thu, Mar 04, 2010 at 01:06:42PM -0500, Ali Razavi wrote:<br>
> Why doesn't this work the way it's supposed to, or the way it's intuitively<br>
> apparent from the code, that is, showing the prompt first, getting the line<br>
> next, and printing the result finally?<br>
><br>
> main = do<br>
> putStr "Please Enter Your Name: "<br>
> name <- getLine<br>
> putStrLn ("Hello " ++ name)<br>
><br>
><br>
> changing putStr with putStrLn rectifies it to the expected behavior, but I<br>
> wonder why this version misbehaves. FWIW, I use ghc in cygwin.<br>
><br>
> Ali<br>
<br>
</div></div>This is because of output buffering. By default, LineBuffering is<br>
used, which means that the runtime will collect output in a buffer<br>
until seeing a newline, at which point it will actually print the<br>
buffer contents on the screen. This is why changing the putStr to<br>
putStrLn makes it work. You can turn off output buffering like so:<br>
<br>
import System.IO<br>
<br>
main = do hSetBuffering stdout NoBuffering<br>
<div class="im"> putStr "Please Enter Your Name: "<br>
</div> ... etc.</blockquote><div><br></div><div>If you don't want a newline after the prompt you can use `hFlush stdout` to manually flush the buffer.</div><div><br></div><div>Cheers,</div><div>Johan</div>
<div> </div></div>