[comp.lang.c] getting input from keyboard

davidd@wolf.cs.washington.edu (David Doll) (12/31/90)

Hello,
	Inside of some "C" code, I want to be able to get a single char(or 
number) from the user without them having to type a carriage return. For 
example:
	crunch,crunch, etc.
	prompt user for some letter, have them hit "y" and then more
	crunch, etc.

Heres a segment of code I tried:

--------------------------------------------------------
#include <stdio.h>
#include <curses.h>

/* 
  to compile: cc -o run test.c -lcurses -ltermcap
*/

main()
{
	int ch;
	int i;
	cbreak();
	for (i=0; i<10; i++){
	 ch=getchar();
	 putchar(ch+1);
	 putchar('\n');
	}
	nocbreak();
}

-------------------------------------------------------
but when I run "run" it accepts the char but at the end (at the end of the for
loop), it frezzes up the keyboard...I'm sure this is simple but I'm missing
what's in front of me :) Could you e-mail me and I'll post a summary if
theres interest. Thanks for the help and wisdom, I appriciate it.

--
David Doll
Computer Science Dept.
University of Washington
Seattle, WA 98195
M/S: FR-35
davidd@wolf.cs.washington.edu

mike@bria.AIX (Michael Stefanik) (01/01/91)

In article <DAVIDD.90Dec30195511@wolf.cs.washington.edu>, davidd@wolf.cs.washington.edu (David Doll) writes:
> Hello,
> 	Inside of some "C" code, I want to be able to get a single char(or 
> number) from the user without them having to type a carriage return.

I'm assuming that you have the termio stuff, but here is a little ditty
to get a single character from the keyboard:

#include <stdio.h>
#include <termio.h>

int getch()
{
struct termio   old, new;
char            c;
int             ret;

        ioctl(0,TCGETA,&old);
        memcpy(&new,&old,sizeof(struct termio));

        new.c_lflag &= ~ICANON;
        new.c_lflag &= ~ECHO;
        new.c_cc[VMIN] = 1;
        new.c_cc[VTIME] = 0;

        ioctl(0,TCSETA,&new);

        if ( read(0,&c,1) != 1 )
                ret = EOF;
        else
                ret = (int)c;

        ioctl(0,TCSETA,&old);
        return(ret);
}
-----------------------------------------------------------------------------
Michael Stefanik, Systems Engineer (JOAT), Briareus Corporation
UUCP: ...!uunet!bria!mike
"If it was hard to code, it should be harder to use!"