[Haskell-beginners] Keyboard input

Daniel Fischer daniel.is.fischer at web.de
Mon Dec 7 17:36:10 EST 2009

Am Montag 07 Dezember 2009 22:52:42 schrieb legajid:
> Hello,
> ok for the responses.
> However, about the strange behaviour of getChar, i forgot to say i'm
> running on Windows XP with GHci 6.10.4

Voilà, c'est ton problème ;)
Somehow, buffering (or rather not buffering) doesn't work properly on Windows. Ordinarily, 
in ghci, stdin is unbuffered, meaning each character you type is immediately passed to the 
application (for binaries, you'd have to "hSetBuffering stdin NoBuffering"), that seems 
not to be the case on Windows (http://hackage.haskell.org/trac/ghc/ticket/2189).

> It seems that getChar buffers all characters, including newline; so,
> typing A + enter is equivalent to typing 2 characters successively.
> To successfully solve the problem, i did the following :
> guessLetter :: IO Char
> guessLetter = do
>     putStrLn "Guess a letter (9 to end): "
>     cl <- getLine
>     let c= extr cl
>     -- c <- getChar
>     -- putChar '\b'
>     return (toUpper c)
> extr :: String -> Char
> extr (c:cs)=c
> Notice that, on my system, putChar has no visible effect.

Buffering again.  Just to test what works, you can try
ghci> :m +System.IO
ghci> hSetBuffering stdout NoBuffering
ghci> putChar 'A'
(turning off buffering for stdout *may* work, even if it doesn't for stdin)
if the next line you see is
it worked

b) explicitly flush stdout

do ...
   putChar 'X'
   hFlush stdout
> Seeking for info, i found this mail :
> http://old.nabble.com/How-to-getCh-on-MS-Windows-command-line--td20414545.h
>tml that talks about a similar issue on Windows
> Didier.

More information about the Beginners mailing list