GCC环境下C语言getch()函数替代方案求助(井字棋代码适配)
GCC环境下井字棋程序的getch()替代及异常修复
1. 替代getch():自定义无回显单字符输入函数
GCC不支持conio.h,可以通过termios库实现类似getch()的功能——无需回车即可获取单个字符,且不回显到终端:
#include <termios.h> #include <unistd.h> int my_getch() { struct termios oldt, newt; int ch; tcgetattr(STDIN_FILENO, &oldt); newt = oldt; newt.c_lflag &= ~(ICANON | ECHO); tcsetattr(STDIN_FILENO, TCSANOW, &newt); ch = getchar(); tcsetattr(STDIN_FILENO, TCSANOW, &oldt); return ch; }
之后直接用my_getch()替代原代码中的getch()即可。
2. 修复清屏命令异常
cls是Windows专属命令,Linux/macOS下需使用clear,通过条件编译实现跨平台清屏:
#include <stdio.h> void clear_screen() { #ifdef _WIN32 system("cls"); #else system("clear"); #endif }
调用clear_screen()替代原代码中的system("cls")。
3. 解决平局误判异常
使用getchar()时,输入数字后按下的回车会留在输入缓冲区,导致程序后续读取到多余的换行符,误触发平局逻辑。使用上述自定义的my_getch()可以避免这个问题,因为它会直接读取输入的单个字符,且不会遗留缓冲区垃圾。
修复后的核心输入逻辑示例
// 获取玩家输入的格子编号 int get_player_input() { int input; printf("请输入1-9的数字选择格子:"); do { input = my_getch() - '0'; // 转换字符为数字 // 验证输入是否合法 if (input < 1 || input > 9) { printf("\n输入无效,请重新输入1-9的数字:"); } } while (input < 1 || input > 9); return input; }
内容的提问来源于stack exchange,提问作者vu nick
相关产品推荐
相关产品推荐

