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

Console.ReadLine()失效:控制台跳过输入无法读取用户名的问题求助

解决Console.ReadLine()被跳过的问题

问题根源是Console.Read()仅读取输入的单个字符,但你输入字符后按下的回车键(换行符)会残留在输入缓冲区,后续调用Console.ReadLine()时会直接读取这个剩余的换行符,导致看起来跳过了输入请求。

修复方案

方案一:改用Console.ReadLine()读取字符

通过读取整行输入再提取首字符,同时自动清空缓冲区:

Console.WriteLine("Now enter a character to search for:");
string charInput = Console.ReadLine();
char userChar = charInput[0]; // 取输入的第一个字符

方案二:清空Console.Read()后的缓冲区

在Console.Read()后额外调用一次Console.ReadLine(),读取残留的换行符:

Console.WriteLine("Now enter a character to search for:");
char userChar = (char)Console.Read();
Console.ReadLine(); // 清空缓冲区中的换行符

修复后的完整代码(方案一示例)

class Program
{
    static void Main(string[] args)
    {
        Console.WriteLine("Please enter a string here and press enter.");
        string user = Console.ReadLine();

        Console.WriteLine("Now enter a character to search for:");
        string charInput = Console.ReadLine();
        char userChar = charInput[0];

        Console.WriteLine($"The index of the letter {userChar} is {user.IndexOf(userChar)}");

        Console.WriteLine("What is your first name?");
        string myNameFirst = Console.ReadLine();
        Console.WriteLine(myNameFirst);
    }
}

内容的提问来源于stack exchange,提问作者AnnetheCyberLady9

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.19 08:17:06