我找不到Linux中与conio.h等价的头文件。
在Linux中是否有getch()
和getche()
函数的选项?
我想制作一个基于switch case的菜单,用户只需按一个键即可选择选项并继续处理。 我不想让用户在按下选择后再按ENTER键。
#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, ¤t); /* 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;
}
输出:
(getche example) please type a letter: g
You typed: g
(getch example) please type a letter...
You typed: g
#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;
}
如果您不想显示字符,则删除最后一个printf
。
我建议您使用curses.h或ncurses.h,它们实现了包括getch()在内的键盘管理例程。您有多种选项可以更改getch()的行为(例如等待按键或不等待)。
在ncurses库中有一个getch()函数。您可以通过安装ncurses-dev包来获取它。
你可以像其他答案所提到的那样,在 Linux 中使用 curses.h
库。
你可以通过以下方式在 Ubuntu 中安装:
sudo apt-get update
sudo apt-get install ncurses-dev
我从这里取得了安装部分的内容。
_getch
,在<conio.h>中。 - Paul Steliannew
是 C++ 中的关键字,但不是 C 中的。 - Paul Steliannew.c_lflag &= ECHO
是不正确的,它将清除除ECHO之外的所有位,应该是new.c_lflag |= ECHO
。 - RedSoft