问题
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.
My code compiles and works perfectly on windows. However, this assignment has to run on linux, and when I try to do so, it tells me it does not recognize getch()
(or _getch()
).
The problem is that according to the assignment, I can not use other includes but stdio.h
(and same goes for adding a flag), so I can not use curses.h
to solve this.
I also can not use termios.h
and so on, we have not learned it.
How can I solve this? Are there any other options?
Thanks
回答1:
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.
回答2:
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.
来源:https://stackoverflow.com/questions/20023537/using-input-function-in-c-on-linux-without-pressing-enter