in C one could read a single character from the keyboard with functions like getc() or getchar(). What is the equivalent in C++? streams use buffered input so how to do it?
This code does not force the user to exit input mode after 1 key is pressed:
1 2
char x;
cin >> x;
Then you also need to discard the rest of the characters entered...
in C one could read a single character from the keyboard with functions like getc() or getchar(). What is the equivalent in C++? streams use buffered input so how to do it?
Do you want the function to return immediately a char is entered or have to wait until a line termination char is entered? .read()/.get() etc will wait until a line termination char has been entered before they return (even if 1 char is requested).
If you want the function to return immediately a char is entered then I'm not aware of this in standard c++. If you have conio.h include file (windows) then there's _getch()/_getche().
While the curses library is for Linux there are ports for Windows. Two readily available for use via vcpkg. ncurses and pdcurses.
I can not say if either of those has getch available or how to set up the terminal. I have neither the time nor interest to learn yet another 3rd party library when standard C++20/23 are at the top of my 'to learn' queue.
As with many 3rd party libraries ncurses functionality is not as easy to use as <conio.h>, it requires a bit of nudging to initialize and proper shutdown to work.
Gee, there are Windows libraries which require a similar initialization/shutdown procedure to work. DirectX and the Common Controls libraries are two examples.
you would think this would be simple or easy, but it isn't. I tried to do this for a while, and without inline assembler, I could not do it. C++ is not set up to read the hardware directly, which is what you need... you need to tap the keyboard interrupts as they happen, at a lower level than c++ gives you access to.
I don't understand the specific, negative comparison with the C library. The C functions have the same limitations as their C++ equivalents. Both are buffered.
1 2 3 4 5 6 7 8 9 10
#include <stdio.h>
int main(void)
{
int ch = getc(stdin); // input: Aaaaa
printf("%d\n", ch); // output: 65 (A)
int ch2 = getc(stdin);
printf("%d\n", ch2); // output: 97 (a)
}
in C one could read a single character from the keyboard with functions like getc() or getchar()
How? As Ganado states above, these c functions are also line buffered. Yes, they will return a single character but only after a line terminator has been entered. Is this what is meant by 'reading a single character'?
What os and c compiler are you using? Can you post the c code you're using for this.