[Haskell-cafe] How to getCh on MS Windows command line?

Matti Niemenmaa matti.niemenmaa+news at iki.fi
Mon Nov 10 12:48:04 EST 2008

Bulat Ziganshin wrote:
> 1. works for me in ghc:
> getHiddenChar = liftM (chr.fromEnum) c_getch
> foreign import ccall unsafe "conio.h getch"
>    c_getch :: IO CInt

Depending on your use case, that's an okay workaround. (And probably suitable
for the OP as well.)

But unfortunately conio doesn't mix well with ordinary IO. For one, it always
reads from the console and not stdin, so redirecting stdin won't work. Another
problem is illustrated in the following:

main = do
   a <- getChar
   b <- getHiddenChar
   c <- getChar
   print a
   print b
   print c

Type a, then press enter, then b. The result (including the echoed input):


I don't know where that '\n' came from but it certainly shouldn't be there.

Yet another example: type abcd, then press enter, giving:


The fact that newlines are reported as '\r' and not '\n' is easy enough to deal
with, but I wonder why getch chose to give '\r' and not 'b'?

More information about the Glasgow-haskell-users mailing list