using input function in C on linux, without pressing enter

谁说我不能喝 提交于 2020-01-25 11:31:47

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!