You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在C#控制台中与用户输入同一行打印文本?

解决C#中Console.ReadLine()后无法在同一行输出的问题

问题根源在于:当用户输入内容并按下回车时,Console.ReadLine()会读取输入的文本(不包含末尾的换行符),但控制台会因为回车操作自动换行,导致后续的Console.Write输出从新的一行开始。

解决方案一:直接拼接输入内容与输出文本

先把用户输入的内容保存到变量中,然后将输入内容和要输出的文本一起通过Console.Write打印,就能实现同一行输出:

using System;

namespace Test {
    class Program {
        static void Main(string[] args) {
            string userInput = Console.ReadLine();
            Console.Write($"{userInput} out");
        }
    }
}

解决方案二:用Console.ReadKey()手动处理输入(适合自定义输入行为)

如果需要避免回车带来的自动换行,可以使用Console.ReadKey()逐个读取输入字符,手动控制回显和结束条件:

using System;
using System.Text;

namespace Test {
    class Program {
        static void Main(string[] args) {
            StringBuilder inputBuilder = new StringBuilder();
            ConsoleKeyInfo keyInfo;
            
            do {
                keyInfo = Console.ReadKey(true); // true表示不自动回显输入的字符
                if (keyInfo.Key != ConsoleKey.Enter) {
                    inputBuilder.Append(keyInfo.KeyChar);
                    Console.Write(keyInfo.KeyChar); // 手动回显输入字符
                }
            } while (keyInfo.Key != ConsoleKey.Enter);
            
            Console.Write(" out");
        }
    }
}

内容的提问来源于stack exchange,提问作者chris.thorpe

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.11 01:55:16