简体   繁体   中英

using input function in C on linux, without pressing enter

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

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 (ie, 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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM