如何捕获用户输入的C# [英] how to trap user inputs C#

查看:41
本文介绍了如何捕获用户输入的C#的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经一个星期学习c#了.事情对我来说是新事物,因为我不熟悉如何编写高效程序的语法和技术.

I've been learning c# by myself for weeks. things are new to me as i am not familiar with the syntax and techniques on how to write an efficient program.

我想知道一个好的程序员如何处理用户输入错误.我的意思是,当我要求用户输入他们的姓名时,

today i wonder how a good programmer deal with user inputs errors. what i mean is, when i ask the users to input their name,

Console.Write(请输入您的姓名");

Console.Write("pls input ur name");

,并且用户输入数字,程序将运行错误.我正在做的是使用字符串变量.

and the user inputs numbers, the program will run onto error. what i am doing is that i use string variable.

字符串输入;

但它会显示所有内容,甚至包括不是名称的数值.

but it displays everything even a numerical value which is not a name.

我该如何处理这种错误?如何捕获用户输入?我如何允许用户仅输入我想要的值?

how could i deal with this kind of error? how can i trap user inputs? how can i allow the user to only input the value i want?

*这是我第一次使用堆栈溢出,感谢您在这里

*this is my first time using stack overflow thanks for having me here

推荐答案

您可以尝试以下操作:

class Program
{

  static void Main()
  {
    string strName;
    do
    {
      Console.WriteLine("What is your name, please?");
      strName = Console.ReadLine();
      foreach ( char c in strName )
        if ( !char.IsLetter(c) )
        {
          Console.WriteLine();
          Console.WriteLine("Your name can only contains letters.");
          Console.WriteLine();
          strName = null;
          break;
        }
    }
    while ( strName == null );
    Console.WriteLine();
    Console.WriteLine("Your name is: " + strName);
    Console.WriteLine();
    Console.WriteLine("Press a key to exit.");
    Console.ReadKey();
  }

}

如果名称可以有空格或任何键,例如'-',则测试条件如下:

If name can have space or any key like '-', the test condition is like:

if ( !char.IsLetter(c) && c!= ' ')

一种高级解决方案是使用一会儿ReadKey()并捕获所有键来编辑和拒绝不是字母的字符,因此用户只能使用字母键.它需要管理诸如箭头,del,退格键,home,end,enter,escape等键,并根据所需的UX重新发送到控制台.

An advanced solution is to use a while ReadKey() and to catch all keys to edit and reject chars that are not letters, so the user can only use letters keys. It requires to manage keys such as arrows, del, backspace, home, end, enter, escape... and to resend to the console according to the UX desired.

这篇关于如何捕获用户输入的C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆