【问题标题】:FormatException when parsing a negative number解析负数时出现FormatException
【发布时间】:2018-10-18 14:11:55
【问题描述】:

所以我有这个代码:

String inputValues = Console.ReadLine();
string[] values = inputValues.Split(" ");
int firstValue = Int32.Parse(values[0]);
int secondValue = Int32.Parse(values[1]);
int thirdValue = Int32.Parse(values[2]);

不知何故,我在 firstvalue-value 上抛出了一个格式异常,说当我在其中输入一个负数(如 -2)时字符串的格式不正确。我还在控制台中得到了一些奇怪的括号,我将我的值放入其中。你可以在我的图片中看到它们。那些是什么,它们是否对我的价值观做了一些事情,因为你肯定可以正确解析负数?

【问题讨论】:

  • 请添加堆栈跟踪。我建议您记录您尝试解析的值是什么(或使用调试器并单步执行)。
  • 用户输入后values的确切值是多少?请仔细检查您最后的Console.WriteConsole.WriteLine 是什么 - 有括号吗?
  • 请也分享您的代码...如果不查看您的代码,就无法判断它有什么问题。
  • 您是否尝试在解析之前修剪值?由于您使用的是 bash,很可能您有一个超级流利的<LF> 或类似的东西。

标签: c# console formatexception


【解决方案1】:

试试这个。

        String inputValues = Console.ReadLine();

        var formatSign = new NumberFormatInfo();
        formatSign.NegativeSign = "−";

        string[] values = inputValues.Split(" ");
        int firstValue = Int32.Parse(values[0],formatSign);
        int secondValue = Int32.Parse(values[1],formatSign);
        int thirdValue = Int32.Parse(values[2],formatSign);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多