C语言getchar()循环仅按回车才打印 如何实现读入字符即输出
问题原因
- 终端默认启用行缓冲输入模式:所有输入的字符会先暂存在系统缓冲区,只有按下回车键后,缓冲区的内容才会被批量提交给程序,所以
getchar()只能在回车后才能读取到输入字符。 - 标准输出默认同样是行缓冲模式:不带换行符的
printf("Hello")输出内容会暂存在进程的输出缓冲区,不会立刻打印到终端界面。
对应修改方案
Linux/macOS 环境
需要手动修改终端配置关闭行缓冲,同时主动刷新输出缓冲区:
#include <stdio.h> #include <termios.h> #include <unistd.h> int main() { int temp; struct termios origin_attr, new_attr; // 读取并保存原始终端配置 tcgetattr(STDIN_FILENO, &origin_attr); new_attr = origin_attr; // 关闭行缓冲模式,可选关闭输入回显 new_attr.c_lflag &= ~(ICANON | ECHO); // 立即应用新的终端配置 tcsetattr(STDIN_FILENO, TCSANOW, &new_attr); while ((temp = getchar())!= EOF) { printf("Hello"); // 主动刷新输出缓冲区,强制立刻打印 fflush(stdout); } // 程序退出前恢复原始终端配置,避免终端行为异常 tcsetattr(STDIN_FILENO, TCSANOW, &origin_attr); return 0; }
Windows 环境
直接使用conio.h提供的_getch()函数即可绕过行缓冲:
#include <stdio.h> #include <conio.h> int main() { int temp; // _getch() 会在按键按下时立刻返回,无需等待回车 while ((temp = _getch())!= EOF) { printf("Hello"); fflush(stdout); } return 0; }
内容的提问来源于stack exchange,提问作者אורי ארצי וייס
相关产品推荐
相关产品推荐

