-1

I was playing around with the Windows Console API and found some interesting behaviour. Using this function:

void defConsole() {
    HANDLE hStdIn = GetStdHandle(STD_INPUT_HANDLE);
    DWORD mode = 0;

    GetConsoleMode(hStdIn, &mode);

    SetConsoleMode(hStdIn, mode & ~(ENABLE_ECHO_INPUT | ENABLE_LINE_INPUT));
}

I was able to make it so that the terminal behaves like non-canonical *nix terminals. (Getchar does not wait for enter and doesn't display what you write, like conio.h's getch or unistd.h's getpass). I then tried printing each character written along with its ascii(?) value.

int main() {
    char c;
    defConsole();

    while (1) {
        c = getchar();
        printf("%c %d\n", c, (int)c);
    }
}

However, something interesting happened: When I pressed enter, nothing happened, but the next key I pressed would be overriden by it (ascii code 13), and the next key would print both the last one and itself.

Why does this happen? What can I do to stop this? Should I change it to use winapi's keyboard input functions instead? That seems like an overkill to me.

1 Answers1

2

To conform with C's line-ending standards, \r\n must be replaced with \n. But you can't know if the sequence is \r\n until you get the character after the \r, so it must be buffered until the next character comes in. Try typing Ctrl-J (\n) after the Enter to see what happens.

Mark Ransom
  • 299,747
  • 42
  • 398
  • 622