在Haskell命令行应用程序中提示输入密码 [英] Prompting for a password in Haskell command line application
本文介绍了在Haskell命令行应用程序中提示输入密码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
以下Haskell程序提示用户在终端中输入密码,如果输入了正确的密码,则继续操作:
The following Haskell program prompts the user for a password in the terminal and continues if he has entered the correct one:
main = do
putStrLn "Password:"
password <- getLine
case hash password `member` database of
False -> putStrLn "Unauthorized use!"
True -> do
...
不幸的是,密码会在用户键入时显示在屏幕上,我想避免这种情况.
Unfortunately, the password will appear on the screen as the user types it, which I want to avoid.
如何在不显示在屏幕上的情况下读取用户键入的字符序列?为此,
getLine
等于什么?
我使用的是MacOS X,但我希望它也可以在Windows和Linux上使用.
I'm on MacOS X, but I would like this to work on Windows and Linux, too.
推荐答案
执行以下操作:
module Main
where
import System.IO
import Control.Exception
main :: IO ()
main = getPassword >>= putStrLn . ("Entered: " ++)
getPassword :: IO String
getPassword = do
putStr "Password: "
hFlush stdout
pass <- withEcho False getLine
putChar '\n'
return pass
withEcho :: Bool -> IO a -> IO a
withEcho echo action = do
old <- hGetEcho stdin
bracket_ (hSetEcho stdin echo) (hSetEcho stdin old) action
这篇关于在Haskell命令行应用程序中提示输入密码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文