【问题标题】:Input validation with integer and int.tryparse [duplicate]使用整数和 int.tryparse 进行输入验证 [重复]
【发布时间】:2018-12-27 22:49:04
【问题描述】:

所以我几乎有 2k 行代码,我忘记了/我不知道如何对用户输入进行输入验证,例如

cw("Hello Please Enter your age");
                cw("If you are in a Group Input the Age of the Youngest Member of the Group.");
                Age = Convert.ToInt32(Console.ReadLine());

我想让它让用户只能输入数字,当他们输入 somthing els 时我的程序不会崩溃。

这是我的 console.readlines 整个程序中的一个常见问题。

有没有一种方法可以让我只对数字和字母进行输入验证?

提前谢谢你。

【问题讨论】:

  • 您可以使用 int.TryParse 来解决您的问题。
  • 是的(尽管我已经有好几年(/几十年)没有写过一个直接的控制台程序了)。编写一个简单的小函数,它接受提示和帮助字符串,并返回一个布尔值(true = 成功,false = 用户决定退出)。在该例程中,输出提示字符串并读取用户的响应。他可以“Q”,请求“H”elp 或输入适当的值(在本例中为int)。然后检查“Q”或“H”。如果两者都不是,请使用int.TryParse 并在失败时循环返回。
  • 哦,拜托,我确定这是一个骗局,但您指的是一个没有公认答案的问题。我看到的第一个使用正则表达式测试数字。如果您向下滚动大约 6 个答案,您会找到使用 TryParse 的 5 票答案(我看到的最后一个答案(12 票)也引用了 TryParse)。必须有更好的人来指出这一点!!!

标签: c#


【解决方案1】:

这就是我要做的(经过多一点润色):

 public static bool PromptForInt(string promptString, out int result, string helpString = null)
 {
     while (true)
     {
         Console.WriteLine(promptString);
         var response = Console.ReadLine();
         if (string.Equals(response, "Q", StringComparison.OrdinalIgnoreCase))
         {
             result = 0;
             return false;
         }

         if (helpString != null && string.Equals(response, "H", StringComparison.InvariantCultureIgnoreCase))
         {
             Console.WriteLine(helpString);
             continue;   //skip back to the top of the loop
         }

         if (int.TryParse(response, out result))
         {
             return true;
         }
     }
 }

您可以将类似的函数用于其他类型(例如,doubleDateTime,始终使用 typeName.TryParse。 在优化方面,如果用户没有输入“Q”、“H”或有效的int,您可能希望获得有用的错误消息。否则……

【讨论】:

    猜你喜欢
    • 2013-02-20
    • 2013-02-20
    • 1970-01-01
    • 2015-07-01
    • 2015-07-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多