using input function in C on linux, without pressing enter

后端 未结 2 981
盖世英雄少女心
盖世英雄少女心 2021-01-27 08:37

I wrote a code on windows, using the function getch() from stdio. The thing is I have to use an input function that does not require pressing enter.

相关标签:
2条回答
  • 2021-01-27 09:06

    We don't do miracles in Linux. You either use other things besides stdio.h, or go without any equivalent of getch and do depend on Enter being pressed.

    0 讨论(0)
  • 2021-01-27 09:18

    The library approach on UNIXes is to us ncurses but it is a bit of a framework which isn't entirely trivial to set up. The non-library mode is to turn the standard input stream into non-canonical input mode using tcgetattr() and tcsetattr() with the file descriptor 0. Typing the necessary code from memory (i.e., I can't test it now and I probably forgot something important) the corresponding code looks something like this:

    struct termios setings;
    tcgetattr(0, &settings);
    settings.c_lflags &= ~ICANON;
    tcsetattr(0, &settings);
    

    Clearly, a real implementation would verify that the system calls are actually successful. Note that after this code std::cin and stdin will immediately react on key presses. As a direct consequence, all kind of "funny" characters will be passed through. For example, when the delete key is used you'll see backspace characters (ctrl-H, char(7)) show up.

    0 讨论(0)
提交回复
热议问题