Haskell: read input character from console immediately, not after newline

前端 未结 4 426
暗喜
暗喜 2020-12-09 08:17

I\'ve tried this:

main = do
    hSetBuffering stdin NoBuffering 
    c <- getChar

but it waits until the enter is pressed, which is not

4条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-09 08:35

    Yes, it's a bug. Here's a workaround to save folks clicking and scrolling:

    {-# LANGUAGE ForeignFunctionInterface #-}
    import Data.Char
    import Foreign.C.Types
    getHiddenChar = fmap (chr.fromEnum) c_getch
    foreign import ccall unsafe "conio.h getch"
      c_getch :: IO CInt
    

    So you can replace calls to getChar with calls to getHiddenChar.

    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.

提交回复
热议问题