getc won't do it. It still requires you to press the enter key. |
getc()
simply reads the next character from the stream. Not more, not less 😀
When reading from the
stdin
in a console application – and if
stdin
was
not redirected from a file – you are effectively reading from a
pipe that is connected to the terminal. But
when exactly does the terminal push the user's input into the the "write" end of the pipe? That's totally up to the terminal's inner workings!
You can
not change this on "your" side, but you may be able to configure the terminal.
In Windows, a terminal has the flag
ENABLE_LINE_INPUT
set by default. This means the terminal itself waits until a full line is completed before passing the input on to the application! You can disable this behavior:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
|
#include <stdio.h>
#include <io.h>
#include <ConsoleApi.h>
static BOOL disable_console_line_input_win32(FILE *const stream)
{
const HANDLE con_handle = (HANDLE) _get_osfhandle(_fileno(stream)); // <-- that is how you obtain a "raw" Win32 handle from a FILE*
DWORD mode;
if (GetConsoleMode(con_handle, &mode)) // <-- get the current console mode first
{
return SetConsoleMode(con_handle, mode & (~ENABLE_LINE_INPUT)); // <-- update console mode with ENABLE_LINE_INPUT removed!
}
return FALSE;
}
int main()
{
setvbuf(stdin, NULL, _IONBF, 0); // <-- just to be sure that there's no additional buffering in the C runtime I/O layer
disable_console_line_input_win32(stdin); // <-- the real "magic" happens here!
for (;;)
{
const char c = getc(stdin);
printf("You typed: '%c'\n", c);
}
return 0;
}
|
Works fine for me, on Windows.
This clearly is very
platform-specific. But I don't think it can be done with just C/C++ standard library functions. You'll have to resort to Win32 API on Windows, and probably to POSIX API on Linux/BSD systems.
For Linux, have a look at "Solution 2" here:
https://localcoder.org/linux-equivalent-for-conio-h-getch