Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

windows

input

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.

like image 939
SSight3 Avatar asked Feb 23 '23 21:02

SSight3


2 Answers

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.

like image 182
Kerrek SB Avatar answered Mar 07 '23 16:03

Kerrek SB


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;
}
like image 42
SChepurin Avatar answered Mar 07 '23 17:03

SChepurin