linux 不回车直接读取一个字符的方法

windows下面有 getch() 可以直接输入一个字符,而不需按回车。

linux下如果想直接输入一个字符,只能使用getchar() ,而且要按回车才能触发输入,否则会一直阻塞在输入这里。网上找到一个解决办法,稍加改进,能实现跟windows下 getch() 一样的效果。

代码如下:添加头文件就可以直接使用了。


#include <stdio.h>

#ifdef _WIN32 //Linux platform
    #include <conio.h>
#else
    #include <termios.h>
#endif

char get1char(void)
{

#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

    int ret = 0;
    char c;

#ifdef _WIN32
    c = getch();
#else
    c = getchar();
    putchar('\b'); // 删除回显
#endif

    printf("input:  [%c]\n", c);

#ifdef _WIN32
    // Do nothing
#else
    tcsetattr (0, TCSANOW, &stored_settings); // 恢复终端参数
#endif

    return c; 
}






参考:http://www.cppblog.com/fwxjj/archive/2007/07/16/28112.html

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值