3

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.

2
  • Your code works perfectly fine for me. Perhaps you're using it wrong. How are you calling it? Commented Feb 27, 2017 at 20:47
  • 3
    Are you sure you are using putStrLn like in the above code, and not putStr? It sounds like a buffering problem. Commented Feb 27, 2017 at 21:05

1 Answer 1

5

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)
Sign up to request clarification or add additional context in comments.

2 Comments

AFAIK line buffering should be the default in all sane implementations when stdout is connected to a terminal. If this works I would still look for the root cause elsewhere.
This fixed it, thanks. and @user2847643, I'll look into it.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.