在Linux(GCC)中,可以使用以下代码示例来实现“无回显”并避免按下回车键时使用getch()函数:
#include
#include
#include
#include
int getch() {
struct termios oldattr, newattr;
int ch;
tcgetattr(STDIN_FILENO, &oldattr);
newattr = oldattr;
newattr.c_lflag &= ~(ICANON | ECHO);
tcsetattr(STDIN_FILENO, TCSANOW, &newattr);
ch = getchar();
tcsetattr(STDIN_FILENO, TCSANOW, &oldattr);
return ch;
}
int main() {
char ch;
printf("Press any key to continue: ");
ch = getch();
printf("\nYou pressed: %c\n", ch);
return 0;
}
在上述示例中,我们使用了termios.h头文件中的结构体和函数来实现“无回显”。getch()函数用于获取用户输入的字符,而不会显示在终端上。我们通过修改终端的属性,关闭了规范模式(ICANON)和回显模式(ECHO)。
要编译和运行上述代码,可以使用以下命令:
gcc -o program program.c
./program
在终端中,按下任意键后,程序将打印出您所按下的字符,并在新的一行中显示。