I'm on Ubuntu. When I run ghci
on Terminal and do this:
Prelude Control.Monad System.IO> forever $ getChar >>= print
The result is something like this:
a'a'
b'b'
C'C'
%'%'
\'\\'
1'1'
''\''
"'"'
^X'\CAN'
^?'\DEL'
^CInterrupted.
That is, the characters I type in my keyboard are being flushed into output. How can I prevent this and have only print
as the writer?
Flushing output on a buffered stream means transmitting all accumulated characters to the file. There are many circumstances when buffered output on a stream is flushed automatically: When you try to do output and the output buffer is full.
When referring to computer memory, the input buffer is a location that holds all incoming information before it continues to the CPU for processing. Input buffer can be also used to describe other hardware or software buffers used to store information before it is processed.
The function fflush(stdin) is used to flush or clear the output buffer of the stream. When it is used after the scanf(), it flushes the input buffer also. It returns zero if successful, otherwise returns EOF and feof error indicator is set.
Using “ fflush(stdin) ”: Typing “fflush(stdin)” after “scanf()” statement, also clears the input buffer but generally it's use is avoided and is termed to be “undefined” for input stream as per the C++11 standards.
To prevent input being flushed into the output (or "echoed"), use hSetEcho stdin False
.
Prelude> import System.IO
Prelude System.IO> import Control.Monad
Prelude System.IO Control.Monad> hSetEcho stdin False
Prelude System.IO Control.Monad> forever $ getChar >>= print
'a'
'\n'
'b'
'c'
This can be used to do things like read in a password.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With