Console.ReadLine()不起作用——它没有要求用户输入,控制台直接跳过了它。

3
这是我的代码。只是写一个简单的程序来练习字符串和使用它的方法。我无论如何都不能让控制台读取我想要存储在变量"myNameFirst"中的"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:");
            char userChar = (char)Console.Read();

            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);

        }
    }
}

我已经重新启动了计算机,重新安装了Visual Studio,确保没有拼写错误。我还搜索了其他的问题,但似乎没有人知道如何修复控制台跳过行的问题。

清楚一点:它完全没有停下来询问输入吗? - Slava Knyazev
对我来说,它运行得很好:https://dotnetfiddle.net/CwhcBT - Slava Knyazev
@SlavaKnyazev 对我来说,它只是跳过了最后一个 Console.ReadLine() 和之后的代码。 - AnnetheCyberLady9
1个回答

4
当你使用Console.Read()时,你只读取一个字符(比如a),但实际上输入的是a和换行符\n。当到达最后一行的Console.ReadLine()时,它不会阻塞,因为缓冲区中已经有一个\n在等待,所以myNameFirst为空。
为了确认这一点,将最后一行改为:
Console.WriteLine("My first name is: " + myNameFirst);
// Print out: My first name is: 

为了解决这个问题,使用额外的Console.ReadLine()来清除“换行”。
char userChar = (char)Console.Read();
Console.ReadLine(); // Add this

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接