Question

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

Était-ce utile?

La solution

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.

Autres conseils

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;
}
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top