Reputation: 53
I need to be able to get the current character being pressed without stopping the program entirely. Ideally, I would like the program to continue running, checking for the key after every iteration of a while loop. getch()
is problematic for this reason. I want to break out of a while loop when the 'q' key is pressed, but for the while loop to continue running until then. I am using Linux with gcc as my compiler.
Upvotes: 2
Views: 853
Reputation: 1
In practice, you should use a library and it depends if you are writing a terminal application or a GUI one.
For terminal applications, read the TTY demystified page and use ncurses or readline. Be aware that in cooked mode (which is the default case), a tty has a kernel-managed line buffer, hence getting a single character thru getc
is not possible. See also termios(3) and tty(4) and tty_ioctl(4) (you could take the pain the set the tty in raw mode -e.g. as in http://shtrom.ssji.net/skb/getc.html suggested in a comment by sjr-, but I recommend using a library).
For graphical applications running on a desktop, use some toolkit like GTK or Qt.
BTW, in both cases the programming model is no more compatible with the naive getc
function.
Read also Advanced Linux Programming and be aware that Linux has several multiplexing system calls (these are listed in syscalls(2)), notably poll(2) -which is probably used by ncurses or readline or Qt or Gtk libraries.
Upvotes: 7