Is there a way to get text as soon as possible wit

2019-03-04 08:52发布

I'm using C. I wrote a very simpe program which prints back the input, using getchar() and putchar() or printf(). Is there any way to make it so as soon as the user types one key, the program registers it, without waiting for an Enter? Let me show:

Currently, if the user types "abc" and then presses Enter, the program prints "abc" and a newline and keeps waiting for more input. I want to make it so as soon as the user types "a", the program prints "a" and waits for more input. I'm not sure whether this has to be done inside the source code or if something has to be changed in the Windows command line.

Just in case, here's the source code:

#include <stdio.h>

int main()
{
    int c;

    while ((c = getchar()) != EOF) {
        putchar(c);
    }
    return 0;
}

4条回答
我命由我不由天
2楼-- · 2019-03-04 09:30

If you're using Visual Studio, you can use getch().

查看更多
The star\"
3楼-- · 2019-03-04 09:32

On Linux you can take over the terminal:

#include <stdio.h>
#include <ctype.h>
#include <termios.h>

system("stty raw"); /* raw output to terminal, direct feedback */
system("clear"); /* clear screen */

printf("Press a key");
answer = getchar();

system("stty cooked"); /* revert back*/
查看更多
男人必须洒脱
4楼-- · 2019-03-04 09:33

if you are using Visual Studio, there is a library called conio (#include <conio.h>) which defines a kbhit() function and getch().

otherwise, on Windows, there is still the possibility of using functions from the Windows SDK (ReadConsoleInput() and the like), but that would require a little bit more code (although, once done and if done properly, it can be reused any time you want)

查看更多
男人必须洒脱
5楼-- · 2019-03-04 09:40

In this simple case, the other answers should suit you fine.

The general solution is to disable line buffering. This depends on the particular console; the following example is Windows-only (untested):

#include <windows.h>

int main() {
    HANDLE hConsole = GetStdHandle(STD_INPUT_HANDLE);
    DWORD mode;
    GetConsoleMode(hConsole, &mode);
    SetConsoleMode(hConsole, mode & ~ENABLE_LINE_INPUT);
    // ...
}

I assume that the standard C library functions are implemented in terms of ReadConsole and friends; if not, this might not even work. (I'm currently on Linux, so I cannot test this.)

查看更多
登录 后发表回答