Haskell:立即从控制台读取输入字符,而不是在换行之后
我已经尝试过这个:
main = do
hSetBuffering stdin NoBuffering
c <- getChar
但它会等到按下回车键,这不是我想要的。我想在用户按下该字符后立即读取该字符。
我在 Windows 7 上使用 ghc v6.12.1。
编辑:我的解决方法是从 GHC 迁移到 WinHugs,它可以正确支持此功能。
I've tried this:
main = do
hSetBuffering stdin NoBuffering
c <- getChar
but it waits until the enter is pressed, which is not what I want. I want to read the character immediately after user presses it.
I am using ghc v6.12.1 on Windows 7.
EDIT: workaround for me was moving from GHC to WinHugs, which supports this correctly.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
是的,这是一个错误。这里有一个避免人们点击和滚动的解决方法:
因此您可以将对
getChar
的调用替换为对getHiddenChar
的调用。请注意,这只是 Windows 上 ghc/ghci 的解决方法。例如,winhugs 没有该错误,并且此代码在 winhugs 中不起作用。
Yes, it's a bug. Here's a workaround to save folks clicking and scrolling:
So you can replace calls to
getChar
with calls togetHiddenChar
.Note this is a workaround just for ghc/ghci on Windows. For example, winhugs doesn't have the bug and this code doesn't work in winhugs.
可能是一个错误:
http://hackage.haskell.org/trac/ghc/ticket/ 2189
Might be a bug:
http://hackage.haskell.org/trac/ghc/ticket/2189
嗯..实际上我不认为这个功能是一个错误。当您读取 stdin 时,这意味着您想要使用“文件”,而当您关闭缓冲时,您表示不需要读取缓冲区。但这并不意味着模拟该“文件”的应用程序不应使用写入缓冲区。对于 Linux,如果您的终端处于“icanon”模式,它不会发送任何输入,直到发生某些特殊事件(例如按下 Enter 或 Ctrl+D)。 Windows 中的控制台可能有一些类似的模式。
Hmm.. Actually I can't see this feature to be a bug. When you read
stdin
that means that you want to work with a "file" and when you turn of buffering you are saying that there is no need for read buffer. But that doesn't mean that application which is emulating that "file" should not use write buffer. For linux if your terminal is in "icanon" mode it doesn't send any input until some special event will occur (like Enter pressed or Ctrl+D). Probably console in Windows have some similar modes.Haskeline 包为我工作。
如果您需要单个字符,只需稍微更改示例即可。
getInputLine
变为getInputChar
"quit"
变为'q'
++ input
变为 <代码>++ [输入]The Haskeline package worked for me.
If you need it for individual characters, then just change the sample slightly.
getInputLine
becomesgetInputChar
"quit"
becomes'q'
++ input
becomes++ [input]
来自@Richard Cook 的评论 :
使用hidden-char:提供跨平台的getHiddenChar函数。
From comment of @Richard Cook:
Use hidden-char: Provides cross-platform getHiddenChar function.
我使用了 haskeline 包,在其他答案中建议,将这个简单的替代方案放在一起
getChar
。在getInputChar
返回Nothing
的情况下,它会再次请求输入。这对我解决这个问题很有帮助;根据需要修改。I used the haskeline package, suggested in other answers, to put together this simple alternative to
getChar
. It requests input again in the case thatgetInputChar
returnsNothing
. This worked for me to get past the issue; modify as needed.