从控制台应用程序同步读取按键 [英] synchronous keystroke reading from console application

查看:107
本文介绍了从控制台应用程序同步读取按键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想立即从Windows和linux下用c编写的控制台应用程序中读取每个按键.不幸的是,当按下输入/返回"键时,函数gets(line)只会返回一个值. 我正在寻找一个可以在按下某个键后立即返回的函数.

I want to read every keystroke from a console application written in c under windows and linux immediately. Unfortunately the function gets(line) does only return a value, when the "enter/return" key is pressed. I'm looking for a function that returns immediately after a key has been pressed.

当前我的代码如下:

char cTmp[MAX_LINE];
char line[MAX_LINE];
while( gets(line) != NULL) {
    sprintf(cTmp,"Characters entered: %c", line);
    puts(cTmp);
}

推荐答案

以下代码对我有用.谢谢您指出我正确的方向. http://bytes.com/topic/c/answers/503640-getch-linux

The following code worked for me. Thank you for pointing me into to right direction. http://bytes.com/topic/c/answers/503640-getch-linux

#include <termios.h>
#include <unistd.h>

int mygetch(void)
{
struct termios oldt,
newt;
int ch;
tcgetattr( STDIN_FILENO, &oldt );
newt = oldt;
newt.c_lflag &= ~( ICANON | ECHO );
tcsetattr( STDIN_FILENO, TCSANOW, &newt );
ch = getchar();
tcsetattr( STDIN_FILENO, TCSANOW, &oldt );
return ch;

}

这篇关于从控制台应用程序同步读取按键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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