While translating an old Basic game to C, I found myself needing a function to get one character from the keyboard. This you You can't do this with common standard C library functions like getchar(3)getchar()
because the standard input stream is line buffered. iline-buffered (i.e. it will store a whole line of input, including a \nthe terminating \n
, in its internal buffer even though getchar()although getchar()
only uses theits first character from it. Subsequent calls to getchar()getchar()
will useconsume buffer's remaining characters from the buffer until it is exhausted and only then will it resume accepting input the user types from the keyboarduser's new inputs). This causes problems because if you need inputinputting twice, the second time you will get some unexpected value instead of giving theletting user a chance to enter aentering second character.
Now, I know the way around this is to use operating system calls such as ioctl(2)ioctl
and read(2)read
to set input to an unbuffered state and read a character (or better yet use a library like CursesCurses
which abstracts away all this in a cross-platform way.) but I started wondering if it was possible to do this entirely via the standard C library.
My first attempt was to empty out the remaining characters in stdin'sstdin
's buffer by adding a call to:
...after calling getchar()getchar()
but this didn't do anything.
My next attempt was to try and take stdinstdin
out of line buffer mode like this:
I had high hopes this would work but actually it seems calling setvbufsetvbuf
on stdinstdin
is undefined behavior. It certainly does not work on Linux.