将String数组解析为Int Matrix

时间:2016-09-21 18:52:10

标签: c# parsing

  string[] words;
  numOfMatrix = int.Parse(fileIn.ReadLine());

  nameOfMatrix1 = fileIn.ReadLine();
  words = fileIn.ReadLine().Split(' ');
  matrix1H = int.Parse(words[0]);
  matrix1W = int.Parse(words[1]);
  matrix1 = new int[matrix1H + 1, matrix1W + 1];
  for (int i = 1; i <= matrix1H; i++)
  {
    int k = 0;
    words = fileIn.ReadLine().Split(' ');
    for (int j = 1; j <= matrix1W; j++)
    {
      matrix1[i,j] = int.Parse(words[k]);
      k++;
    }
  }

输入样本数据

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

未处理的异常:System.FormatException:输入字符串的格式不正确。    at System.Number.StringToNumber(String str,NumberStyles options,NumberBuffer&amp; number,NumberFormatInfo info,Boolean parseDecimal)    在System.Number.ParseInt32(String s,NumberStyles样式,NumberFormatInfo信息)    在System.Int32.Parse(String s)

在我将字[k]解析为matrix1 [i,j]的行上,我收到一条错误消息。 Parse在我第一次使用单词[]时工作正常但不是第二次读到的东西。

1 个答案:

答案 0 :(得分:-2)

问题是从内循环内部读取下一行。您需要读取行而不是每个单元格的行。

var numOfMatrix = int.Parse(fileIn.ReadLine().Trim());
var matrices = new int[numOfMatrix][,];
for (var matrixNumber = 0; matrixNumber < numOfMatrix; matrixNumber++)
{
    var nameOfMatrix1 = fileIn.ReadLine().Trim();
    var words = fileIn.ReadLine().Trim().Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
    var matrix1H = int.Parse(words[0]);
    var matrix1W = int.Parse(words[1]);

    var matrix1 = matrices[matrixNumber] = new int[matrix1H, matrix1W];            
    // don't use <=
    for (int i = 0; i < matrix1H; i++)
    {
        // read line line outside of the inner loop
        words = fileIn.ReadLine().Trim().Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
        // don't use <=
        for (int j = 0; j < matrix1W; j++)
        {
            matrix1[i, j] = int.Parse(words[j]);
        }
    }
}