开发者

Get an input from keyboard without 'return' in C

How do i get an input开发者_JS百科 from keyboard, without pressing 'return' in C / Mac Os


On Unix-like systems with terminals (I suppose that MacOS X qualifies), then you need to set the terminal to so-called "cbreak" mode. The point is that the terminal is keeping the data until "return" is pressed, so that there is nothing your C code can do, unless it instructs the terminal not to do such buffering. This is often called "cbreak mode" and involves the tcsetattr() function.

A bit of googling found this code which seems fine. Once the terminal is in cbreak mode, you will be able to read data as it comes with standard getchar() or fgetc() calls.


From the comp.lang.c FAQ: How can I read a single character from the keyboard without waiting for the RETURN key? How can I stop characters from being echoed on the screen as they're typed?


If you have to handle the details yourself, use a curses variant. If it is available, prefer "ncurses" over "curses". Note that some keys are "Meta" keys which really just modify the base key codes. There are several "modes" for reading key input, which range from "cooked", through "partially cooked", to "raw". Each mode has its own peculiarities, read the documentation carefully.

Sometimes it's better to use existing key handling code from various game programming libraries, I've heard of some good results using SDL's key scanning loops. That was a while back, so perhaps newer (and better) toolkits exist.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜