haskell-跳过getLine [英] haskell -skipping getLine
问题描述
嘿-优秀的编码人员和散客, 我是Haskell新生,程序有问题 归结为以下情况
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'
除main的首次执行外的任何内容
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
按预期执行,我愿意接受任何建议和帮助 在此先感谢ε/2
is executed as expected, i'm open for any suggestions and help thanks in advance ε/2
推荐答案
解决方法:在程序开始时设置NoBuffering
:
The fix: set NoBuffering
at the start of your program:
hSetBuffering stdin NoBuffering
为什么这可以解决问题?查看不使用NoBuffering时要输入的内容!您键入,并且getLine
使用:
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]
然后键入,getLine
#2会消耗:
Then you type, and getLine
#2 consumes:
second input[enter]
然后键入:
y[enter]
但是getChar
只消耗了y
并保留了[enter]
缓冲,这是您的第一个getLine
调用读取的内容!为什么输入[enter]
?因为您必须这样做,所以只需单击'y'并不会导致main
循环,因为终端是行缓冲的.
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.
这篇关于haskell-跳过getLine的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!