Greg
Greg

Reputation: 33

Haskell - Taking input during runtime

I'm new to Haskell and I can't figure out how to accept input from the user during code execution. Say I type this code:

import System.IO

main = do  
    putStrLn "Hi, what's your name?"  
    name <- getLine  
    putStrLn ("Hi " ++ name)

Well, I want the text "Hi, what's your name?" to show up before I type in my name, then print the second line "Hi, name" after the user types their name. However, as it is right now, none of the text shows up until after I type my name. This makes the question redundant, since the question is not presented to the user until after they have answered it.

I know this may be a noobish question, but I've been googling it for a long time with no success. Thanks for your time.

Upvotes: 3

Views: 120

Answers (1)

Chad Gilbert
Chad Gilbert

Reputation: 36385

It is probably due to the default buffering on your system. Try explicitly setting the buffering modes to line buffering using hSetBuffering:

main = do
    hSetBuffering stdout LineBuffering
    hSetBuffering stdin LineBuffering
    putStrLn "Hi, what's your name?"  
    name <- getLine  
    putStrLn ("Hi " ++ name)

Upvotes: 5

Related Questions