读取行直到ESC按钮进入haskell

时间:2012-06-11 19:36:22

标签: haskell line stdin

我需要实线直到按下ESC按钮。我怎么检查呢?

lines
   = do
      line <- getLine
      if (== "/ESC") --this condition is wrong
         then ...
         else do
            ln <- lines
            return ...

有人可以解决我的问题吗?

1 个答案:

答案 0 :(得分:3)

正确的转义方法是使用反斜杠,字符为'\ESC',因此条件为

if line == "\ESC"

但我不确定每个终端都会将'\ESC'传递给应用程序。

如果你想在按下 ESC 键时立即停止,那么

module Main (main) where

import System.IO

main :: IO ()
main = do
    hSetBuffering stdin NoBuffering
    getUntilEsc ""

getUntilEsc :: String -> IO ()
getUntilEsc acc = do
    c <- getChar
    case c of
      '\ESC' -> return ()
      '\n' -> do putStrLn $ "You entered " ++ reverse acc
                 getUntilEsc ""
      _ -> getUntilEsc (c:acc)

是你需要的。你必须阅读字符,你需要关闭stdin的缓冲,这样字符就可以立即读取,而不仅仅是在输入换行后。

请注意,在Windows上关闭缓冲功能无效。我不知道最近是否修复过这个问题。 此外,正如@Daniel Wagner报道的那样,很可能Windows命令提示符未将 ESC 传递给应用程序。