linux中类似getch的函数,c-Linux中的getch()和getche()等效于什么?

c-Linux中的getch()和getche()等效于什么?

我在Linux中找不到conio.h的等效头文件。

Linux中是否有getch()和getche()函数的选项?

我要创建一个切换案例基础菜单,用户只需按一个键就可以给出选项,并且过程应该向前移动。 我不想让用户按其选择后按ENTER。

6个解决方案

70 votes

#include

#include

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;

}

输出:

(getche example) please type a letter: g

You typed: g

(getch example) please type a letter...

You typed: g

niko answered 2019-11-09T01:53:49Z

31 votes

#include

#include

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。

mf_ answered 2019-11-09T01:54:14Z

7 votes

我建议您使用curses.h或ncurses.h来实现包括getch()在内的键盘管理例程。 您可以通过多种方式来更改getch的行为(即是否等待按键)。

Fafaman answered 2019-11-09T01:54:38Z

5 votes

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

Jan S answered 2019-11-09T01:55:02Z

0 votes

您可以按照其他答案中所述在Linux中使用curses.h库。

您可以通过以下方式在Ubuntu中安装它:

sudo apt-get更新

须藤apt-get install ncurses-dev

我从这里开始安装。

Ashish Ahuja answered 2019-11-09T01:55:49Z

0 votes

如上所述,getch()位于ncurses库中。 ncurses必须初始化,请参见getchar()为此返回上下箭头键相同的值(27)

ralf htp answered 2019-11-09T01:56:15Z

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值