Getting a single character without pressing enter

Juicy picture Juicy · Sep 25, 2015 · Viewed 8.1k times · Source

I'm trying to get a single character input from the user without the user having to press enter. I've tried this:

#include <stdio.h>

int main() {
    int input;

    for (;;) {
        input = getchar();
        printf("%d\n", input);
    }
}

But not only does the user need to press enter, it also registers two presses (the input character and the newline character) ie:

$ ./tests
a
97
10
c
99
10

Since I will always expect exactly one character input from the user, and want this character as either a char or an int, how can I get the character without waiting for a \n.

I also tried using fgets, but because I'm in a loop waiting for user input, that just continously executes the printf without blocking until input.

My expected output would be:

a97
b98
...

NB: I'm currently on OSX but I'm happy with a solution that applies to either OSX or Linux.

Answer

syntagma picture syntagma · Sep 25, 2015

I have recently needed exactly the same feature and I have implemented it in the following way:

#include <stdlib.h>

char c;

system("/bin/stty raw");
c = tolower(getchar());
system("/bin/stty cooked");

Looking at man stty, I think it should work on both Linux and Mac OS X.

EDIT: So your program would look like (you would need to add a signal handler to it):

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

int main() {
    int input;

    for (;;) {
        system("/bin/stty raw");
        input = getchar() - '0';
        printf("%d\n", input);
        system("/bin/stty cooked");
    }
    return 0;
}