什么是等价于 getch() &Linux 中的 getche() ? [英] What is the equivalent to getch() & getche() in Linux?

查看:25
本文介绍了什么是等价于 getch() &Linux 中的 getche() ?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am not able to find the equivalent header file for conio.h in Linux.

getch() 是否有任何选项 &getche() Linux 中的函数?

Is there any option for getch() & getche() function in Linux?

我想制作一个 switch case 基本菜单,用户只需按一个键就可以给出他的选项 &进程应该向前推进.我不想让用户按他的选择后按 ENTER.

I want to make a switch case base menu where the user will give his option just by pressing one key & process should be moved ahead. I don't want to let user to press ENTER after pressing his choice.

推荐答案

#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("
You typed: %c
", c);
  printf("(getch example) please type a letter...");
  c = getch();
  printf("
You typed: %c
", c);
  return 0;
}

输出:

(getche example) please type a letter: g
You typed: g
(getch example) please type a letter...
You typed: g

这篇关于什么是等价于 getch() &amp;Linux 中的 getche() ?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆