2015-03-13 100 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