这是我的密码.只需编写一个简单的程序来练习字符串及其方法.我无论如何也不能让控制台读取我想存储在变量"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,我判断了一下,以确保没有打字错误.我还搜索了其他问题,似乎没有人知道如何跳过这些问题来修复游戏机.

推荐答案

当您使用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

Csharp相关问答推荐

.请求()不适用于Azure AD B2C的C#

如何在Shell中创建WinUI 3图形界面?

.NET通过版本自动增量设置包版本

EF Core. Income和. AsNoTracking正确用法

如何循环遍历XML文档 node 以使用XSLT存储值

SignalR客户端不会打印队列位置'

Unity中的刚体2D运动

此反射有什么问题.是否发送值转换委托?

MudBlazor—MudDataGrid—默认过滤器定义不允许用户修改基本过滤器

具有单一导航属性的EF核心一对多关系

Azure DEVOPS找不到定制的Nuget包

try 在.Net核心身份注册页面中使用AJAX,但没有成功..NET Core 5.0 Razor页面应用程序

如何在不复制或使用输出的情况下定义项目依赖

使用switch 类型模式时出现奇怪的编译器行为

Celler ArgumentExpression是否期望在所有情况下都捕获允许空值的运算符?

C# Winforms:从对象树到TreeView的递归转换重复条目

如何对特定异常使用Polly重试机制?

为什么我在使用有效令牌的情况下仍未获授权?

如何解决System.StackOverflowException:抛出System.StackOverflowException类型的异常.&# 39;生成随机代码时发生异常?

如何将 colored颜色 转换为KnownColor名称?