Jul 5, 2024 at 7:43am UTC
read a single character from the keyboard |
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().
Last edited on Jul 5, 2024 at 7:44am UTC
Jul 5, 2024 at 4:26pm UTC
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.
Jul 5, 2024 at 5:19pm UTC
You have to use the OS/terminal facilities to turn off line-buffered input (to “raw” input)
AND to obtain the key press.
Meaning, there is no easy cross-platform way to do it. I assume you are still messing with Windows?
Check out the
Windows Console functions (
https://learn.microsoft.com/en-us/windows/console/console-functions). In particular,
SetConsoleMode()
and
ReadConsoleInput()
.
Last edited on Jul 5, 2024 at 5:19pm UTC
Jul 8, 2024 at 3:14pm UTC
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)
}
|
1 2 3 4 5 6 7 8 9 10 11 12 13
|
#include <iostream>
using namespace std;
int main()
{
char ch;
cin >> ch; // input: Aaaaa
cout << (int)ch << '\n'; // output: 65 (A)
char ch2;
cin >> ch2;
cout << (int)ch2 << '\n'; // output: 97 (a)
}
|
Last edited on Jul 9, 2024 at 1:46pm UTC
Jul 8, 2024 at 3:47pm UTC
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.
Last edited on Jul 8, 2024 at 3:52pm UTC