【发布时间】: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