【问题标题】:FormatException was unhandled occursFormatException was unhandled 发生
【发布时间】:2014-11-15 07:59:58
【问题描述】:

我已经在我的 C# 控制台应用程序中声明了字符数组。

我的代码:

char[] address = new char[30];
char[] blood_Grp = new char[10];

public void getdata()
{
    Console.WriteLine("enter your address");

    // here I am getting FormatException was unhandled exception 
    address[i] = Convert.ToChar(Console.ReadLine());
}    

请帮我解决我的编码问题..

【问题讨论】:

  • 请编辑您的帖子并使用代码标签来格式化您的代码,并包含您获得异常的堆栈跟踪。

标签: c#


【解决方案1】:

问题是您正在阅读完整的一行(chars 的数组)。如果输入的长度大于1,则会抛出FormatException

你应该使用Console.ReadKey()

address[i] = Console.ReadKey().KeyChar;

它有一个属性KeyChar,所以你不需要自己把它转换成char

【讨论】:

    【解决方案2】:

    Console.ReadLine 将返回字符串

    那么你可以使用String.ToCharArray 来获取字符

    【讨论】:

      【解决方案3】:

      试试

      string address = Console.ReadLine();
      

      或者...

      char[] address = Console.ReadLine().ToCharArray();
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-04-28
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-04-07
        • 2013-12-10
        • 2023-03-22
        • 2023-01-28
        相关资源
        最近更新 更多