SE Does Not Like Dissent
SE Does Not Like Dissent

Reputation: 1835

Real-time keyboard input to console (in Windows)?

I have a doubly-linked list class, where I want to add characters to the list as the user types them, or removes the last node in the list each time the user presses backspace, whilst displaying the results in console in real-time.

What functions would I use to intercept individual keyboard input, and display it in real-time to the console? So the following results:

User starts typing:

Typ_

User stops typing:

Typing this on screen_

User presses backspace 5 times:

Typing this on s_

Particular OS is windows (vista, more specifically).

As a side-note GetAsyncKeyState under windows.h appears to perhaps be for keyboard input, however the issue of real-time display of the console remains.

Upvotes: 4

Views: 13433

Answers (3)

SChepurin
SChepurin

Reputation: 1854

You will be surprised, but this code will do what you want:

/* getchar example : typewriter */
#include <stdio.h>

int main ()
{
  char c;
  puts ("Enter text. Include a dot ('.') in a sentence to exit:");
  do {
    c=getchar();
    putchar (c);
  } while (c != '.');
  return 0;
}

Upvotes: 3

ixe013
ixe013

Reputation: 10191

You could use ReadConsoleInput, adding incoming caracters to your list, look for the backspace keys (INPUT_RECORD->KEY_EVENT_RECORD.wVirtualScanCode == VK_BACKSPACE) and removing the last caracter from your list for all of them.

Upvotes: 2

Kerrek SB
Kerrek SB

Reputation: 477620

C++ has no notion of a "keyboard". It only has an opaque FILE called "stdin" from which you can read. However, the content of that "file" is populated by your environment, specifically by your terminal.

Most terminals buffer the input line before sending it to the attached process, so you never get to see the existence of backspaces. What you really need is to take control of the terminal directly.

This is a very platform-dependent procedure, and you have to specify your platform if you like specific advice. On Linux, try ncurses or termios.

Upvotes: 4

Related Questions