什么等同于Linux中的getch()和getche()?

Jee*_*tel 57 c linux getch getchar getc

我无法在Linux中找到conio.h的等效头文件.

在Linux中有getch()&getche()function功能吗?

我想制作一个开关盒基本菜单,用户只需按一个键即可提供选项,并且应该向前移动过程.按下他的选择后,我不想让用户按ENTER键.

nik*_*iko 70

#include <termios.h>
#include <stdio.h>

static struct termios old, current;

/* Initialize new terminal i/o settings */
void initTermios(int echo) 
{
  tcgetattr(0, &old); /* grab old terminal i/o settings */
  current = old; /* make new settings same as old settings */
  current.c_lflag &= ~ICANON; /* disable buffered i/o */
  if (echo) {
      current.c_lflag |= ECHO; /* set echo mode */
  } else {
      current.c_lflag &= ~ECHO; /* set no echo mode */
  }
  tcsetattr(0, TCSANOW, &current); /* use these new terminal i/o settings now */
}

/* Restore old terminal i/o settings */
void resetTermios(void) 
{
  tcsetattr(0, TCSANOW, &old);
}

/* Read 1 character - echo defines echo mode */
char getch_(int echo) 
{
  char ch;
  initTermios(echo);
  ch = getchar();
  resetTermios();
  return ch;
}

/* Read 1 character without echo */
char getch(void) 
{
  return getch_(0);
}

/* Read 1 character with echo */
char getche(void) 
{
  return getch_(1);
}

/* Let's test it out */
int main(void) {
  char c;
  printf("(getche example) please type a letter: ");
  c = getche();
  printf("\nYou typed: %c\n", c);
  printf("(getch example) please type a letter...");
  c = getch();
  printf("\nYou typed: %c\n", c);
  return 0;
}
Run Code Online (Sandbox Code Playgroud)

只需复制这些功能并使用它.我很久以前在google上找到了这个片段而且我已经保存了它,最后我在很长一段时间后为你打开它!希望它有所帮助!谢谢

  • 谢谢,它有效,但我不得不用其他东西替换**新**因为它是我猜的关键字 (4认同)
  • @MihaiVilcu `new` 是 C++ 中的关键字,但不是 C 中的关键字。 (2认同)
  • 该示例中有一个错误:当echo为true时,new.c_lflag&= ECHO不正确,它将清除除ECHO之外的所有位,应为new.c_lflag | = ECHO。 (2认同)

mf_*_*mf_ 31

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

char getch(void)
{
    char buf = 0;
    struct termios old = {0};
    fflush(stdout);
    if(tcgetattr(0, &old) < 0)
        perror("tcsetattr()");
    old.c_lflag &= ~ICANON;
    old.c_lflag &= ~ECHO;
    old.c_cc[VMIN] = 1;
    old.c_cc[VTIME] = 0;
    if(tcsetattr(0, TCSANOW, &old) < 0)
        perror("tcsetattr ICANON");
    if(read(0, &buf, 1) < 0)
        perror("read()");
    old.c_lflag |= ICANON;
    old.c_lflag |= ECHO;
    if(tcsetattr(0, TCSADRAIN, &old) < 0)
        perror("tcsetattr ~ICANON");
    printf("%c\n", buf);
    return buf;
 }
Run Code Online (Sandbox Code Playgroud)

复制此功能并使用它,不要忘记包含

printf

  • @mr-32 这在 Linux 中与 Visual Studio for Windows 使用的 getch() 完全相同,减去该函数最后一行的 printf() (2认同)

Faf*_*man 7

我建议你使用curses.h或ncurses.h这些实现键盘管理例程,包括getch().您有几个选项可以更改getch的行为(即等待是否按下按键).


Jan*_*n S 5

ncurses库中有一个getch()函数。您可以通过安装ncurses-dev软件包来获得它。

  • 在一种情况下,我不想为此安装新东西……还有其他选择吗? (2认同)
  • 您需要编写自己的函数-如niko所示。 (2认同)