Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Read keyboard input

Status
Not open for further replies.

freeindy

Programmer
Jan 14, 2003
4
SE
Hi,

I want to get keyboard character when pressed. I have the following code (and i've tried many others...). But the character is only recieved when pressed CR. How can I instantly get the character when it is pressed?

thanks in advance
Indy

char getCommand(void)
{
int hDevice;
char key[1];
char command = 0;

hDevice = open("/dev/pts/0", O_RDONLY | O_NONBLOCK);

if(read(hDevice, key, 1) == -1)
command = 0;
else
command = key[0];

return command;
}
 


Well, you haven't specified if you're in X-Windows or a terminal, nor if you're using SVGALib if you're in a terminal. However, if you ARE in a terminal, get NCurses and do a little reading of MAN NCURSES. There's a routine in there that does exactly what you're looking for, for a variety of get combos (doesn't getch() or getc() do what you want, too?).
If you REALLY REALLY REALLY want the specific function, yell and I'll dig it up with parameters.

"The reward of patience is patience"
-St. Augustine
 
here a simple code ...

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <curses.h>

char * ready(const char *);

int main(void)
{
char * wordy;

wordy = ready(&quot;\nwrite your texte : &quot;);

printf(&quot;\n result is : %s\n&quot;, wordy);

return 0;
}

char * ready(const char * invite)
{
static char tmp[256];
int c,i=0;

printf(invite);

while( (c=getchar()) != '\n' )
{
tmp=c;
i++;
putchar(c);
}
return tmp;
}


You can write more nicer things, like char * tmp and care with the realloc stuff, so you are not borned with the 256. care more about the \0

but this code do what I think you wanted to do


hope it helps


lcout
 
Those examples don't address the fundamental question of line discipline, how standard input isn't flushed to a receiving process until a newline is encountered. In the example above getchar() is never said to be unbuffered I/O l(like &quot;read&quot; from fd 0 with a 1 byte length).

Here is the real answer:

 
Likewise there is also curses... Although, I can't find any good documentation on them, nor see a reason to use them (yet)
 
*******************************************************************
you need to use unbuffered I/O routines,here is a code sample.

Code:
#include <conio.h>

void main()
{
	int ch;
	while(( ch = getch() ) != 26 ) // stops with CTRL-Z
	{
		cprintf(&quot; character = %c   ascii code = %d&quot;, ch, ch );
		cprintf(&quot;\r\n&quot;);
	}
}
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top