C#输入矩阵从文本文件崩溃

时间:2016-09-25 18:04:19

标签: c#

这是我目前的源代码..

CODE:

static void InputValues()
{
  int row, col;
  string[] words;

  matrixName = fileIn.ReadLine();
  words = fileIn.ReadLine().Split(' ');
  dimenOne = int.Parse(words[0]);
  dimenTwo = int.Parse(words[1]);
  matrix = new int[dimenOne+1, dimenTwo+1];
  for (row = 1; row <= dimenOne; row++)
  {
    words = fileIn.ReadLine().Split(' ');
    for (col = 1; col <= dimenTwo; col++)
    {

      matrix[row, col] = int.Parse(words[col-1]);
    }
  }
}

之后读取45的第一个值后,我的程序会崩溃

matrix[row, col] = int.Parse(words[col-1]);文本文件中的值之间有3个空格,位于下方。如何在不崩溃的情况下填充二维数组?

TXT FILE

3
Matrix One
5 7
45   38    5   56   18   34    4
87   56   23   41   75   87   97
45   97   86    7    6    8   85
67    6   79   65   41   37    4
 7   76   57   68    8   78    2
Matrix Two
6 8
45   38    5   56   18   34    4   30
87   56   23   41   75   87   97   49
45   97   86    7    6    8   85   77
67    6   79   65   41   37    4   53
 7   76   57   68    8   78    2   14
21   18   46   99   17    3   11   73
Matrix Three
6 6
45   38    5   56   18   34
87   56   23   41   75   87
45   97   86    7    6    8
67    6   79   65   41   37
 7   76   57   68    8   78
21   18   46   99   17    3

2 个答案:

答案 0 :(得分:0)

测试是否可以将值转换为整数(使用TryParse)或更好地使用正则表达式来解析输入字符串。你的问题是split函数返回的结果比你预期的要多(如果在words = filein ....之后设置一个断点,很容易看到)。

答案 1 :(得分:0)

如果你的行中有可变数量的空格,你应该删除它们。

words = fileIn.ReadLine()
              .Split(' ')
              .Where(x => !string.IsNullOrWhiteSpace(x))
              .ToArray();