2

This is my code

main :: IO ()  
main = do
    putStr "Enter user name: " 
    userName <- getLine
    putStr "Enter filename: " 
    fileName <- getLine
    contents <- readFile fileName
    --------SOME CODES HERE------------------
    putStrLn ("TITLES AND RATINGS OF FILMS BY " ++ userName)
    -----------SOME CODES HERE-----------------
    putStr "ENTER 'Y' TO SAVE CHANGES AND EXIT: "
    ex <- getChar
    if ex /= 'Y' then
       main     
    else do 
        writeFile fileName (show film')
        exitWith ExitSuccess 

When I enter any value asides from 'Y' I get:

Enter user name: Enter filename: _

instead of just

Enter user name: _

Anyone know why this is happening?

  • 1
    You're printing both strings before the if statement, so why do you expect only the first to be printed? – Frank Schmitt Mar 13 '14 at 10:24
  • http://stackoverflow.com/questions/2500459/wrong-io-actions-order-using-putstr-and-getline http://stackoverflow.com/questions/13190314/haskell-do-monad-io-happens-out-of-order – radomaj Mar 13 '14 at 10:25
  • I expect the prompt to wait till I enter a user name before asking me to enter a filename. What it does when the if condition is true is it asks me for both the user name and filename on the same line. I hope this is clear – user3414726 Mar 13 '14 at 10:31

1 Answers1

4

getChar only reads a single character. But you pressed enter, so you've also entered a newline which is then read by the first getLine when you recursively call main.

Simply use getLine instead of getChar and check that it is /= "Y".

Tobias Brandt
  • 3,393
  • 18
  • 28