C#来自文本文件的输入矩阵崩溃
这是我目前的源代码 代码:C#来自文本文件的输入矩阵崩溃,c#,C#,这是我目前的源代码 代码: 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,
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]);
}
}
}
测试是否可以将值转换为整数(使用TryParse),或者最好使用正则表达式来解析输入字符串。您的问题是split函数返回的结果比您预期的要多(如果在words=filein….之后设置断点,则很容易看到)如果行中的空格数可变,则应消除它们
words = fileIn.ReadLine()
.Split(' ')
.Where(x => !string.IsNullOrWhiteSpace(x))
.ToArray();
如何使用regex解析输入字符串?我以前从未真正使用过它。我看到split将21项放入
单词数组。当我希望它放入7项时,其中7是矩阵中该行的值数。为什么正则表达式更适合从字符串解析整数?您是否尝试过使用string.Split的重载?它会自动删除空条目。我怀疑您的程序正在崩溃,因为尝试将非整数的内容解析为整数。有关可解析数据之间存在可变数量空格时拆分字符串的解决方案,请参阅标记的“重复”。如果您需要更多的帮助,可以通过提供一个可靠地再现问题的好方法来改进您的问题,清楚准确地说明发生了什么错误(包括堆栈跟踪和任何错误消息),并详细描述您试图修复它的内容,以及您遇到的具体困难。
words = fileIn.ReadLine()
.Split(' ')
.Where(x => !string.IsNullOrWhiteSpace(x))
.ToArray();