如何在C语言中实现输入后不换行,使输出紧跟输入内容?
如何让输入数字后光标不跳转到新行,直接在同一行输出后续内容?
问题分析
输入数字按下回车后,终端默认会将回车键转换为换行符,同时scanf仅读取整数部分,不会处理输入缓冲区中剩余的换行符,导致后续输出与输入内容不在同一行。
解决方案
方法1:跨平台文本覆盖法(简单易用)
利用回车符\r将光标移回行首,重新输出输入提示和数字,再衔接后续内容,实现同一行显示:
#include <stdio.h> int main() { int num; printf("Enter a number: "); scanf("%d", &num); // 移回行首,重新输出提示+输入值,再继续后续内容 printf("\rEnter a number: %dYou entered: %d. Next, let's print on the same line: ", num, num); printf("This is the output on the same line.\n"); return 0; }
输出效果:
Enter a number: 10You entered: 10. Next, let's print on the same line: This is the output on the same line.
方法2:Linux/Unix系统下修改终端属性
通过终端属性设置,关闭回车自动转换为换行的功能,从根源避免换行:
#include <stdio.h> #include <termios.h> #include <unistd.h> int main() { struct termios old_attr, new_attr; // 保存当前终端属性 tcgetattr(STDIN_FILENO, &old_attr); new_attr = old_attr; // 禁用回车转换行的ONLCR选项 new_attr.c_oflag &= ~ONLCR; tcsetattr(STDIN_FILENO, TCSANOW, &new_attr); int num; printf("Enter a number: "); scanf("%d", &num); // 清空输入缓冲区剩余的换行符 while(getchar() != '\n'); printf("You entered: %d. Next, let's print on the same line: ", num); printf("This is the output on the same line.\n"); // 恢复终端原有属性 tcsetattr(STDIN_FILENO, TCSANOW, &old_attr); return 0; }
方法3:Windows系统下修改控制台模式
使用Windows API调整控制台输入模式,阻止回车触发换行:
#include <stdio.h> #include <windows.h> int main() { HANDLE hStdin = GetStdHandle(STD_INPUT_HANDLE); DWORD original_mode; // 获取当前控制台模式 GetConsoleMode(hStdin, &original_mode); // 关闭行输入模式,输入字符直接传递 SetConsoleMode(hStdin, original_mode & ~ENABLE_LINE_INPUT); int num; printf("Enter a number: "); scanf("%d", &num); // 清空输入缓冲区 while(getchar() != '\n'); printf("You entered: %d. Next, let's print on the same line: ", num); printf("This is the output on the same line.\n"); // 恢复原有控制台模式 SetConsoleMode(hStdin, original_mode); return 0; }
内容的提问来源于stack exchange,提问作者meghashyaam sagar
相关产品推荐
相关产品推荐

