0

I'm trying to use getchar() to retrieve 1 keystroke at a time from the keyboard. Though it does this, the problem I'm having is doesn't send it immediately, it waits for the enter key to be pressed and then it reads 1 char at a time from the buffer.

int main(){
    char c = getchar();
    putchar(c);

return 0;
}

How do I immediately read each keystroke as it's pressed from the keyboard? Thanks

DangerousDave23
  • 113
  • 1
  • 2
  • 10
  • The answer to this is, unfortunately, platform-specific. On *nix, you have to put the terminal into “raw mode” or use a library that does this for you. – Emmet Mar 19 '14 at 20:28

2 Answers2

1

You have to pass in raw mode. I paste you code from:

http://c.developpez.com/faq/?page=clavier_ecran

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

void mode_raw(int activer)
{
static struct termios cooked;
static int raw_actif = 0;

if (raw_actif == activer)
    return;

if (activer)
{
    struct termios raw;

    tcgetattr(STDIN_FILENO, &cooked);

    raw = cooked;
    cfmakeraw(&raw);
    tcsetattr(STDIN_FILENO, TCSANOW, &raw);
}
else
    tcsetattr(STDIN_FILENO, TCSANOW, &cooked);

raw_actif = activer;

}

After that, you don't need to tap Enter key.

EDIT: Like Emmet says, it's the Unix version, it's depend of the environment.

Julien Leray
  • 1,647
  • 2
  • 18
  • 34
1

You can use the getch() funcion, which is defined in conio.h

Notice that the use of getch() isn't showing the characters on the console. If you wish to see your intput, you can use functions like putch(), putchar(), printf(), etc.

e.g.

#include <conio.h>

int main()
{
     char c = getch();
     putch(c); //isn't necessary for the input, Let's you see your input.
     return 0;
}
alextikh
  • 119
  • 1
  • 9
  • 1
    That's platform specific (originated in Borland C on DOS back in the dark ages). I don't think there's a platform-independent solution. On *Linux*, there's a similar `getch()` in `curses.h` (link with `-lncurses`) that can be used if you have the `libncurses-dev` (or similar, depending on the distribution) package installed. – Emmet Mar 19 '14 at 20:36
  • Hi Alex, I'm using OSX and I don't seem to have the conio.h file. – DangerousDave23 Mar 19 '14 at 20:36
  • Try to install `ncurses` – M.M Mar 19 '14 at 21:11