read char without pressing enter

closed account (DNwq5Di1)
well, i have a while-loop. and the user enters some chars for some different options.

Right now i'm storing the char in a variable with "charVariable = getchar();" but the user got to press enter before continue. Is there a way to the program will continue after the key is pressed (no <return>).

Thanks in advance, Sjums
Look for the ncurses library: http://www.gnu.org/software/ncurses/
For UNIX you can simply select() and read() on file descriptor 0 (stdin).
closed account (DNwq5Di1)
Thanks.. i tried the select() nad read().. but couldn't make it work as i wanted :)

Then i found this function:

1
2
3
4
5
6
7
8
9
10
11
12
13
int getch(void)
{
  int ch;
  struct termios oldt;
  struct termios newt;
  tcgetattr(STDIN_FILENO, &oldt); /*store old settings */
  newt = oldt; /* copy old settings to new settings */
  newt.c_lflag &= ~(ICANON | ECHO); /* make one change to old settings in new settings */
  tcsetattr(STDIN_FILENO, TCSANOW, &newt); /*apply the new settings immediatly */
  ch = getchar(); /* standard getchar call */
  tcsetattr(STDIN_FILENO, TCSANOW, &oldt); /*reapply the old settings */
  return ch; /*return received char */
}
Close! Good job!
http://www.cplusplus.com/forum/articles/7312/#msg33734
(Scroll down for the POSIX stuff.)

The problem with that one is "extended" key codes, which often return a string of character codes instead of a single character code. (For example, if the user presses UP on the keypad.)

Hope this helps.
Topic archived. No new replies allowed.