2015-03-13 101 views
0

将单词转换为int有一个问题。写得不好吗?将字符串转换为int C#并放入数组

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); 

我有错误:

An unhandled exception of type 'System.FormatException' occurred in mscorlib.dll

文件:

0

12 0

19 15 0

31 37 50 0

22 21 36 20 0

17 28 35 21 25 0

+0

什么是要转换的单词?你的'line'看起来像什么? – 2015-03-13 18:54:42

+0

单词是单个单词 – 2015-03-13 18:55:31

+4

发布问题时,请包含所有相关的输入和期望的输出。 (在这种情况下,输入非常重要)。 – 2015-03-13 18:55:37

回答

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"); 
     } 
    } 
} 
+0

非常感谢! :) – 2015-03-13 19:14:04

0

您的字符串不表示一个干净的INT。可能是带小数点的数字? (例如5.5?)要抓住和打印这个词,你可以使用try/catch。

+0

谢谢你的回答。但请确定OP I/P是什么,以及期望的O/P – Backtrack 2015-03-13 18:57:21