haskell -skipping getLine
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
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.
加载中,请稍侯......
精彩评论