【问题标题】:Using getchar to immediately retrieve keystrokes使用 getchar 立即检索击键
【发布时间】:2014-03-19 20:21:15
【问题描述】:

我正在尝试使用 getchar() 从键盘一次检索 1 个击键。虽然它这样做了,但我遇到的问题是没有立即发送它,它等待按下回车键,然后从缓冲区中一次读取 1 个字符。

int main(){
    char c = getchar();
    putchar(c);

return 0;
}

如何在键盘按下时立即读取每个键击? 谢谢

【问题讨论】:

  • 不幸的是,这个问题的答案是特定于平台的。在 *nix 上,您必须将终端置于“原始模式”或使用为您执行此操作的库。

标签: c getchar


【解决方案1】:

您必须以原始模式传递。 我粘贴你的代码:

http://c.developpez.com/faq/?page=clavier_ecran

#include <termios.h>
#include <unistd.h>

void mode_raw(int activer)
{
static struct termios cooked;
static int raw_actif = 0;

if (raw_actif == activer)
    return;

if (activer)
{
    struct termios raw;

    tcgetattr(STDIN_FILENO, &cooked);

    raw = cooked;
    cfmakeraw(&raw);
    tcsetattr(STDIN_FILENO, TCSANOW, &raw);
}
else
    tcsetattr(STDIN_FILENO, TCSANOW, &cooked);

raw_actif = activer;

}

之后,您无需按 Enter 键。

编辑: 就像 Emmet 说的,它是 Unix 版本,它取决于环境。

【讨论】:

  • curses 使用getch() 可能更容易。
【解决方案2】:

您可以使用在 conio.h 中定义的 getch() 函数

请注意,使用 getch() 不会在控制台上显示字符。 如果你想查看你的输入,你可以使用 putch()、putchar()、printf() 等函数。

例如

#include <conio.h>

int main()
{
     char c = getch();
     putch(c); //isn't necessary for the input, Let's you see your input.
     return 0;
}

【讨论】:

  • 这是特定于平台的(起源于黑暗时代的 DOS 上的 Borland C)。我不认为有一个独立于平台的解决方案。在 Linux 上,如果您安装了 libncurses-dev(或类似的,取决于发行版)软件包,则可以在 curses.h(与 -lncurses 的链接)中使用类似的 getch()
  • 嗨,Alex,我使用的是 OSX,但我似乎没有 conio.h 文件。
  • 尝试安装ncurses
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-01-19
  • 1970-01-01
  • 1970-01-01
  • 2013-02-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多