Prompting for a password in Haskell command line application

前端 未结 6 951
傲寒
傲寒 2021-02-01 04:10

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:         


        
6条回答
  •  陌清茗
    陌清茗 (楼主)
    2021-02-01 04:25

    Do this:

    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
    

提交回复
热议问题