zoukankan      html  css  js  c++  java
  • [Linux]从控制台一次读取一个字符,无需等待回车键

                    [Linux]从控制台一次读取一个字符,无需等待回车键

                                      周银辉 

    读取字符嘛,可以使用getchar(),getch()等等函数,但它们都需要等待回车键以结束输入,而不是按下键盘时立即响应,看上去不那么“实时”。

    如果是在windows平台下的话,可以使用conio.h下的_getch()函数,注意是以下划线开头的,msdn链接在这里

    在linux下貌似没有找到类似的函数... 不过可以使用一个比较BT的方式来实现:更改控制台设置。

    #include <termios.h>

    static struct termios oldt;

    //restore terminal settings
    void restore_terminal_settings(void)
    {
        
    // Apply saved settings
        tcsetattr(0, TCSANOW, &oldt); 
    }

    //make terminal read 1 char at a time
    void disable_terminal_return(void)
    {
        
    struct termios newt;
        
        
    //save terminal settings
        tcgetattr(0&oldt); 
        
    //init new settings
        newt = oldt;  
        
    //change settings
        newt.c_lflag &= ~(ICANON | ECHO);
        
    //apply settings
        tcsetattr(0, TCSANOW, &newt);
        
        
    //make sure settings will be restored when program ends
        atexit(restore_terminal_settings);
    }

    下面是一个demo程序,复制粘贴试用吧:

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

    static struct termios oldt;

    //restore terminal settings
    void restore_terminal_settings(void)
    {
        
    //Apply saved settings
        tcsetattr(0, TCSANOW, &oldt); 
    }

    //make terminal read 1 char at a time
    void disable_terminal_return(void)
    {
        
    struct termios newt;
        
        
    //save terminal settings
        tcgetattr(0&oldt); 
        
    //init new settings
        newt = oldt;  
        
    //change settings
        newt.c_lflag &= ~(ICANON | ECHO);
        
    //apply settings
        tcsetattr(0, TCSANOW, &newt);
        
        
    //make sure settings will be restored when program ends
        atexit(restore_terminal_settings);
    }

    int main()
    {
        
    int ch;
        
        disable_terminal_return();
        
        printf(
    "press your keyboard\n");
        
    /* Key reading loop */
        
    while (1) {
            ch 
    = getchar();
            
    if (ch == 'Q'return 0;  /* Press 'Q' to quit program */
            printf(
    "\tYou pressed %c\n", ch);
        }
        
        
    return 0;
    }
     

  • 相关阅读:
    Vue项目中跨域问题解决
    子网掩码
    C++的const类成员函数
    在python3中使用urllib.request编写简单的网络爬虫
    Linux 重定向输出到多个文件中
    背包问题
    hdu-1272 小希的迷宫
    SQLAlchemy 几种查询方式总结
    pycharm快捷键、常用设置、配置管理
    python3判断字典、列表、元组为空以及字典是否存在某个key的方法
  • 原文地址:https://www.cnblogs.com/zhouyinhui/p/1849011.html
Copyright © 2011-2022 走看看