【问题标题】:Return user to point of data entry C# Console application [duplicate]将用户返回到数据输入点 C# 控制台应用程序 [重复]
【发布时间】:2013-09-11 19:53:00
【问题描述】:

在下面的例子中,假设用户输入了一个负数,我怎样才能让光标回到用户输入一个无效数字的地方,这样程序才能继续运行?

Console.Write("Enter a number for the factorial: ");

int k = Convert.ToInt32(Console.ReadLine());

if (k < 0)
{
    Console.WriteLine("Please enter a number that is greater than or equal to zero");
}

【问题讨论】:

  • 当您在搜索引擎中输入“C# 在控制台窗口中移动光标”时发生了什么?
  • “将光标移回用户输入无效数字的位置”是什么意思?

标签: c# validation


【解决方案1】:

我认为这将满足您的要求

string errormessage="Please enter a positive number; previous input was invalid";
        Console.WriteLine("Enter the number: ");
        int k = Convert.ToInt32(Console.ReadLine());
        while (k < 0)
        {
            Console.Write(errormessage);
            //get back to the input line
            Console.SetCursorPosition(0, Console.CursorTop-1);
            //Clearing the previous input
            for (int i = 0; i < k.ToString().Length; i++)
                Console.Write(" ");
            Console.Write("\r");
            k = Convert.ToInt32(Console.ReadLine());
        }
        //Clearing the error message
        for (int i = 0; i < errormessage.Length; i++)
            Console.Write(" ");
        Console.WriteLine("\r");

对不起,不是最漂亮的代码,但可以完成工作!

【讨论】:

    【解决方案2】:

    利用similar post中的方法,相信你可以解决你的问题。基本上只需复制 ClearConsoleLine 方法并使用 Console.SetCursorPosition 移动到所需的行/列。

    【讨论】:

      猜你喜欢
      • 2012-12-21
      • 1970-01-01
      • 2011-08-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多