Terminal input

xiaoxiao2021-03-06  69

In many cases, we want to press the keyboard character in the console, and the program will respond immediately instead of waiting for the carriage return.

You can use getch () (requiring #include "conoe.h") under the Windows platform, and this function cannot be used without this header in the Linux platform. There must be a road before the car to the mountain, and we have another way. Look at the code below: struct termios stored_settings; struct termios new_settings; tcgetattr (0, & stored_settings); new_settings = stored_settings; new_settings.c_lflag & = (~ ICANON); new_settings.c_cc [VTIME] = 0; new_settings.c_cc [VMIN ] = 1; TCSetattr (0, tcsanow, & new_setting); Termios structure describes the terminal's mode, in which the code has changed, allowing the terminal to receive the keyboard input immediately returned. Therefore, you can get the input character using a general read character function getChar (). When you have an exit your program, you have to remember to change the terminal environment: TcSetattr (0, tcsanow, & stored_setting);

These functions and structural requirements include header file Termios.h and stdio.h. Here is a test file that can be compiled under Windows and Linux operating systems:

#include "stdio.h" #include "stdlib.h" #ifdef _win32 // linux platform #include "cono.h" #define get_char getch # Else #include "termitios.h" #define get_char getchar # ENDIF

转载请注明原文地址:https://www.9cbs.com/read-90748.html

New Post(0)