其他语言

本类阅读TOP10

·基于Solaris 开发环境的整体构思
·使用AutoMake轻松生成Makefile
·BCB数据库图像保存技术
·GNU中的Makefile
·射频芯片nRF401天线设计的分析
·iframe 的自适应高度
·BCB之Socket通信
·软件企业如何实施CMM
·入门系列--OpenGL最简单的入门
·WIN95中日志钩子(JournalRecord Hook)的使用

分类导航
VC语言Delphi
VB语言ASP
PerlJava
Script数据库
其他语言游戏开发
文件格式网站制作
软件工程.NET开发
终端输入

作者:未知 来源:月光软件站 加入时间:2005-2-28 月光软件站

    在很多情况下,我们希望在控制台下,按键盘字符,程序马上反应而不是等待回车后才响应。

    在Windows平台下可以使用getch  ()(要求#include “conio.h“)实现,而在Linux平台下没有这个头文件,也就无法使用这个函数。
    车到山前必有路,我们另有办法。
    先看下面这段代码:
struct termios stored_settings;
struct termios new_settings;
tcgetattr (0, &stored_settings);
new_settings = stored_settings;
new_settings.c_lflag &= (~ICANON);
new_settings.c_cc[VTIME] = 0;
new_settings.c_cc[VMIN] = 1;
tcsetattr (0, TCSANOW, &new_settings);
    termios结构的描述了终端的模式,在这段代码中我们改变了它,使得终端能够接收到键盘输入马上返回。所以就能够使用一般的读取字符函数getchar ()来获得输入字符。
    在退出你的程序时,要记得把终端环境改回来:
tcsetattr (0, TCSANOW, &stored_settings);

这几个函数以及结构要求包含头文件termios.h和stdio.h。
    下面是一个测试文件,可以在Windows和Linux操作系统下,编译运行:

#include "stdio.h"
#include "stdlib.h"
#ifdef _WIN32 //Linux platform
    #include "conio.h"
    #define get_char getch
#else
    #include "termios.h"
    #define get_char getchar
#endif

int main (int argc, char* argv[])
{
    #ifdef _WIN32
    //Do nothing
    #else
    struct termios stored_settings;
    struct termios new_settings;
    tcgetattr (0, &stored_settings);
    new_settings = stored_settings;
    new_settings.c_lflag &= (~ICANON);
    new_settings.c_cc[VTIME] = 0;
    new_settings.c_cc[VMIN] = 1;
    tcsetattr (0, TCSANOW, &new_settings);
    #endif
    while (1) {
        char c = get_char ();
        if ('q' == c || 'Q' == c)
            break;
        printf ("You input: %c\n", c);
    }
    #ifdef _WIN32
    //Do nothing
    #else
    tcsetattr (0, TCSANOW, &stored_settings);
    #endif
    return 0;
}
    要提的一点是,getch ()是没有回显的,而getchar ()是有回显的,所以在Windows和Linux下的运行有点不同。




相关文章

相关软件