为了账号安全,请及时绑定邮箱和手机立即绑定

什么是Linux中的Getch()&getche()?

什么是Linux中的Getch()&getche()?

狐的传说 2019-07-01 09:58:19
什么是Linux中的Getch()&getche()?我无法在Linux中找到conio.h的等效头文件。有什么可供选择的吗?getch() & getche()Linux中的函数?我想做一个开关案例基础菜单,用户将提供他的选择,只要按一个键&进程应该向前移动。我不想让用户按回车后,按下他的选择。
查看完整描述

3 回答

?
qq_遁去的一_1

TA贡献1725条经验 获得超7个赞

#include <termios.h>#include <stdio.h>static struct termios old, new;/* Initialize new terminal i/o settings */void initTermios(int echo) {
  tcgetattr(0, &old); /* grab old terminal i/o settings */
  new = old; /* make new settings same as old settings */
  new.c_lflag &= ~ICANON; /* disable buffered i/o */
  if (echo) {
      new.c_lflag |= ECHO; /* set echo mode */
  } else {
      new.c_lflag &= ~ECHO; /* set no echo mode */
  }
  tcsetattr(0, TCSANOW, &new); /* 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;}

只需复制这些函数并使用它。我很久以前就在谷歌上找到了这个片段,我保存了它,最后我为你打开了很长一段时间,希望它能帮助你!谢谢


查看完整回答
反对 回复 2019-07-01
?
POPMUISE

TA贡献1765条经验 获得超5个赞

char getch(){
    /*#include <unistd.h>   //_getch*/
    /*#include <termios.h>  //_getch*/
    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;
 }

复制这个函数并使用它,别忘了包括

remove the last printf if you dont want the char to be displayed


查看完整回答
反对 回复 2019-07-01
  • 3 回答
  • 0 关注
  • 785 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信