[Haskell] How to read one char from stdin and return immediately?

Robert Dockins robdockins at fastmail.fm
Fri Aug 18 09:36:58 EDT 2006


On Aug 18, 2006, at 8:09 AM, Haihua Lin wrote:

>
> Hi all,
>
> How to read one char from stdin and return immediately?
> I mean there is no need to wait the user input a return.
>
> For example:
> Print "y/n: "
> Users input y, return immediately, no return need.
>
> I have tried code as below, but it didn't work for me.
>
> import IO
>
> main = do
>          hSetBuffering stdout NoBuffering
>          putStr   "Y/N: "
>          c <- getChar
>          putStr ("Your input is " ++ show c++".\n")
>
> Thanks very much.
>

I do it this way; it should keep your buffering state consistent even  
if exceptions occur.


  bracket (hGetBuffering stdin) (hSetBuffering stdin) $ \_ -> do
       hSetBuffering stdin NoBuffering
       c <- hGetChar stdin
       return c


> Best regards,
> Haihua Lin



Rob Dockins

Speak softly and drive a Sherman tank.
Laugh hard; it's a long way to the bank.
           -- TMBG





More information about the Haskell mailing list