开发者

synchronous keystroke reading from console application

开发者 https://www.devze.com 2023-02-14 19:15 出处:网络
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\" ke

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 i开发者_JAVA技巧mmediately after a key has been pressed.

Currently my code looks something like this:

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


You're probably looking for getch(). On Windows (at least VC++) it's declared in <conio.h>. On Linux it's part of curses.


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;

}


I think you're looking for getchar() and putchar() :

#include <stdio.h>
char line[MAX_LINE];
int i = 0;
int c;
while ( (c = putchar(getchar())) != EOF)
{
    line[i] =c;
}
0

精彩评论

暂无评论...
验证码 换一张
取 消