控制台应用中如何设置光标前的文本?
控制台应用中如何设置光标前方的文本?
如果你用过ArcInfo Workstation这类命令行应用,肯定见过它根据当前模块切换光标前的标识——比如输入TIN后,提示符会从GRID:>变成TIN:>,光标始终停在标识后方等待输入。
要实现这个效果,核心是自己控制提示符的输出,再读取用户输入,而不是依赖控制台默认的输入流程。下面用两种常见语言举例:
C# 实现示例
using System; class CustomPromptApp { static void Main() { string currentModule = "GRID"; while (true) { // 输出自定义提示符,用Write而非WriteLine,避免光标换行 Console.Write($"{currentModule}:> "); // 读取用户输入 string input = Console.ReadLine(); // 根据输入切换模块提示符 if (string.Equals(input, "TIN", StringComparison.OrdinalIgnoreCase)) { currentModule = "TIN"; } else if (string.Equals(input, "GRID", StringComparison.OrdinalIgnoreCase)) { currentModule = "GRID"; } else if (string.Equals(input, "EXIT", StringComparison.OrdinalIgnoreCase)) { break; } else { Console.WriteLine($"执行命令:{input}"); } } } }
Python 实现示例
current_module = "GRID" while True: # 直接将提示符嵌入input()函数,光标会自动停在提示符后 user_input = input(f"{current_module}:> ") if user_input.lower() == "tin": current_module = "TIN" elif user_input.lower() == "grid": current_module = "GRID" elif user_input.lower() == "exit": break else: print(f"执行命令:{user_input}")
关键要点
- 用
Console.Write()(C#)或直接在input()中嵌入提示符(Python),确保光标停在提示符后方,而非新行。 - 每次循环开始时先输出最新的提示符,再读取用户输入,实现动态切换标识的效果。
- 不需要依赖控制台的
Title属性或WriteLine(),核心是接管输入前的提示符输出逻辑。
内容的提问来源于stack exchange,提问作者Craig Gers
相关产品推荐
相关产品推荐

