嘿 - 伟大的程序员和haskellers,我是一名哈斯克尔大学新生并且有一个程序问题归结为以下情况
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'
Run Code Online (Sandbox Code Playgroud)
除了第一次执行main之外的任何一个
input1 <- getLine
Run Code Online (Sandbox Code Playgroud)
被跳过,我找不到它的理由,如下所示
input2 <- getLine
Run Code Online (Sandbox Code Playgroud)
按预期执行,我对任何建议持开放态度,并提前感谢ε/ 2
修复:设置NoBuffering在程序的开头:
hSetBuffering stdin NoBuffering
Run Code Online (Sandbox Code Playgroud)
为什么这会解决问题?当你不使用NoBuffering时,看看你正在输入什么!您输入并getLine消耗:
first input[enter]
Run Code Online (Sandbox Code Playgroud)
然后键入,getLine#2消耗:
second input[enter]
Run Code Online (Sandbox Code Playgroud)
然后键入:
y[enter]
Run Code Online (Sandbox Code Playgroud)
但是getChar只消耗了y并且离开了[enter]缓冲区,这是您的第一个getLine呼叫读取的!你为什么打字[enter]?因为你必须这样做,只是点击'y'不会导致main循环,因为终端是行缓冲的.