haskell -skipping getLine

懵懂的女人 提交于 2019-12-23 05:13:08

问题


hey - great coders and haskellers, i'm a haskell freshman and have a problem with a program it boils down to the following situaition

main :: IO ()
main = do
    putStrLn "\nplease give me some input"
    input1 <- getLine
    putStrLn "\nplease give me another input"
    input2 <-getLine
    putStrLn ("\nyour inputs were "++show(input1)++" and "++ show(input2)")
    putStrLn "restart ?? yY or nN"
    c <- getChar
    restart c
    where 
    restart c
        |elem c "yY" = do
            main
        |elem c "nN" = putStrLn "\nExample Over"
        |otherwise = do
            putStrLn "\nyou must type one of Yy to confirm or nN to abort"
            c'<- getChar
            restart c'

on any but the first execution of main

input1 <- getLine

is skipped and i can find no reason for it, as the following

input2 <- getLine

is executed as expected, i'm open for any suggestions and help thanks in advance ε/2


回答1:


The fix: set NoBuffering at the start of your program:

hSetBuffering stdin NoBuffering

Why does this fix the issue? Look at what you're typing when you don't using NoBuffering! You type, and getLine consumes:

first input[enter]

Then you type, and getLine #2 consumes:

second input[enter]

Then you type:

 y[enter]

But getChar only consumed the y and leaves the [enter] buffered, which your first getLine call reads! Why did you type [enter]? Because you had to, just hitting 'y' didn't cause main to loop because the terminal was line buffered.



来源:https://stackoverflow.com/questions/5605983/haskell-skipping-getline

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!