C#输入矩阵

问题描述:

这里是目前我的源代码..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文件

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 
+0

您是否尝试过使用[这](https://msdn.microsoft.com/en-us/library/ms131448(V = vs.110)的.aspx)'String.Split'超载?它会自动删除空的条目。我怀疑你的程序崩溃了,因为试图解析一些不是整数的整数。 –

+0

如果可解析数据之间存在可变数量的空格,请参阅标记为用于解决方案的副本以分割字符串。如果您需要更多的帮助,通过提供良好的[MCVE]认为可靠重现问题,清楚准确地正是发生错误(包括堆栈跟踪和任何错误消息)说明,并详细说明您有什么改进你的问题试图解决它,以及你有什么具体的困难。 –

要么测试如果可以(使用的TryParse)或更好的使用正则表达式来解析输入字符串的值转换为整数。你的问题是,分割函数返回更多的结果比预期的。如果你在你行可变数量的空间(可以很容易,如果你的话后设置一个断点= FILEIN可以看出....)

+0

如何使用正则表达式来解析输入字符串?我从来没有真正使用过它。我看到拆分把21个项目放入'words'数组中。当我希望它把7个项目,其中7是该矩阵的那一行的值的数量。 –

+0

http://stackoverflow.com/questions/262480/whats-the-quickest-way-to-extract-a-5-digit-number-from-a-string-in-c-sharp –

+0

为什么正则表达式是更好的从字符串解析整数? – Fabio

,你应该消除它们。

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