【问题标题】:Console hangs on newline after getting user input获取用户输入后控制台挂在换行符上
【发布时间】:2020-02-15 01:47:47
【问题描述】:

我需要这个程序来要求用户输入一个数字以添加到数组中。在他们输入数字后,控制台会转到换行符,直到您按下另一个键,此时它将再次执行相同的操作。我是 C# 的新手,我认为这与它在用户输入信息后读取 enter 键的事实有关,所以我需要使用与 cin.ignore() 等效的东西,但我没有能够找到解决问题的任何方法。

public void InputSet()
{
    int userInput;

    do
    {
        C.Write("Enter an element (Enter to end): ");
        userInput = Convert.ToInt32(C.ReadLine()); // Read user input

        if (userInput < 1 || userInput > 50) // Check if in bounds
            C.WriteLine("Input is invalid. Enter from 1 to 50."); // Error message if out of bounds
        else
        {
            Array.Resize(ref arr, arr.Length + 1); // Expand array and then add it in
            arr[arr.Length - 1] = userInput;
        }
    } while(Console.ReadKey (true).Key != ConsoleKey.Enter); // If enter key is pressed, exit loop

以下是该问题的视频: Hanging on newline

【问题讨论】:

  • 你想清除控制台还是什么,控制台中的一个空行或者你对the console goes to a newline until you press another key的确切含义。
  • @Twenty 我添加了一个关于该问题的简短视频,但基本上在用户输入数字并按 Enter 后,控制台会转到换行符并一直停留在那里,直到您按下另一个键,此时它会提示他们输入另一个数字。我希望它在每次用户输入数字并按 Enter 时继续询问更多数字。

标签: c# user-input


【解决方案1】:

控制台没有挂起 - 它期待输入以继续 while 循环:

while(Console.ReadKey (true).Key != ConsoleKey.Enter);

我已经测试了代码,它运行良好 - 也许您可能想反馈用户要采取什么行动才能完成或继续。

        Console.WriteLine("Press enter to terminate or C to continue");
    } while (Console.ReadKey(true).Key != ConsoleKey.Enter); // If enter key is pressed, exit loop

任何键都可以。

【讨论】:

    【解决方案2】:

    我不完全确定我理解你的问题或问题

    然而,

    1. 您可能应该使用List 而不是数组
    2. 您应该使用int.TryParse 来验证用户输入
    3. 您可能应该使用Console.ReadLine 而不是ReadKey
    4. 可以查看result == string.Empty退出

    示例

    var list = new List<int>();
    
    while (true)
    {
       Console.Write("Enter an element (Enter to end): ");
       var result = Console.ReadLine();
    
       if (result == string.Empty) break;
       if (!int.TryParse(result, out var value))
       {
          Console.WriteLine("You had one job...");
          continue;
       }
       list.Add(value);
    } 
    
    Console.WriteLine(string.Join(", " , list));
    
    Console.ReadKey();
    

    输出

    Enter an element (Enter to end): 2
    Enter an element (Enter to end): 3
    Enter an element (Enter to end): 4
    Enter an element (Enter to end): 6
    Enter an element (Enter to end): f
    You had one job...
    Enter an element (Enter to end):
    2, 3, 4, 6
    

    【讨论】:

    • 教授的专栏指导我们使用数组。我一直看到我应该在我看过的所有线程上使用列表,虽然大声笑
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-12-22
    • 1970-01-01
    • 2013-04-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-02-28
    相关资源
    最近更新 更多