将字符串转换为int C#并放置到数组中

时间:2015-03-13 18:52:11

标签: c#

我有一个问题,将word转换为int。写得不好吗?

foreach (string line in lines)
        {
            string[] words = line.Split(' ');
            foreach (string word in words)
            {

                {
                    tab[i] = Int32.Parse(word);
                    Console.WriteLine(tab[i]);
                    i++;

                }
            }
        }

在这一行:

tab[i] = Int32.Parse(word);

我有错误:

  

未处理的类型' System.FormatException'发生在mscorlib.dll

文件:

  

0

     

12 0

     

19 15 0

     

31 37 50 0

     

22 21 36 20 0

     

17 28 35 21 25 0

2 个答案:

答案 0 :(得分:0)

您的字符串不代表干净的int。可能是带小数位的数字? (例如5.5?)要捕获并打印单词,您可以使用try / catch。

答案 1 :(得分:0)

这意味着您的输入有问题。考虑使用Int.TryParse,假设您只想使用格式良好的整数,这将起作用。您还可以在失败时安装一些输出,以便了解哪些值无法解析,例如,

bool b;
int tempNumber;
foreach (string line in lines)
{
    string[] words = line.Split(' ');
    foreach (string word in words)
    {
        b = Int32.TryParse(word, out tempNumber);
        if (b) // success
        {
            tab[i] = tempNumber;
            Console.WriteLine(tab[i]);
            i++;
        }
        else // handle error
        {
           Console.WriteLine("Error: '" + word + "' could not be parsed as an Int32");
        }
    }
}