如何将矩阵从文件中读取到数组中
本文关键字:读取 数组 文件 | 更新日期: 2024-10-23 21:52:56
嘿,伙计们,我正试图从文本文件中保存一个数组,但我在想如何保存它时束手无策。我可以打印矩阵的所有元素,从文本文件可以看到。
样本输入:
1 2 3 4 5
2 3 4 5 6
3 4 5 6 7
1 2 3 4 5
我一直得到一个超出范围的索引异常。不确定发生了什么。希望你们能理解我的意图。到目前为止,我拥有的是:
class Program
{
static void Main(string[] args)
{
string input =
@"C:'Users'Nate'Documents'Visual Studio 2015'Projects'Chapter 15'Chapter 15 Question 5'Chapter 15 Question 5'TextFile1.txt";
StreamReader reader = new StreamReader(input);
List<string> list = new List<string>();
char[] unwanted = new char[] { ' ' };
using (reader)
{
int row = 0;
int column = 0;
string line = reader.ReadLine();
while (line != null)
{
string[] numbersString = line.Split(unwanted);
int[,] numbersInt = new int [ row, numbersString.Length];
foreach (string a in numbersString)
{
Console.Write("{0} ",a);// this is to check that the array was read in the right order
numbersInt[row, column] = int.Parse(a);
column++;
}
line = reader.ReadLine();
Console.WriteLine();
row++;
}
}
}
}
我建议使用杂耍数组(数组int[][]
的数组),而不是2D的数组;在这种情况下,解决方案将非常简单,类似于以下内容(Linq):
int[][] matrix = File
.ReadLines(@"C:'myFile.txt")
.Split(new Char[] {' ', ''t'}, StringSplitOptions.RemoveEmptyEntries)
.Select(items => items
.Select(item => int.Parse(item))
.ToArray())
.ToArray();
测试(让我们打印出矩阵):
String report = String.Join(Environment.NewLine, matrix
.Select(line => String.Join(" ", line)));
Console.Write(report);
while
中的这一更改应该可以做到:
while (line = file.ReadLine()) != null)
{
...
}
来源:MSDN
您似乎正在while循环中创建numbersInt的实例。这意味着每次循环都将重新创建数组,当循环退出时,数组将丢失。将numberInt的声明移到while循环的外部。
您的直接问题是您的代码在读取每一行后都不会将column
重置回零。将int column = 0
移到while
循环中以解决此问题。
第二个问题是numbersInt
分配。您为每条线创建它,这是不对的,因为它是一个二维数组。你需要在循环之前创建它,但当然不能,因为你不知道会有多少行。一种方法是使用动态数据结构,一次添加一行
通过将File.ReadAllLines
方法与LINQ结合使用,您可以极大地简化代码,因为这将使您摆脱许多简单的代码。现在,您可以在创建2-D阵列之前检查您有多少行,并且您也可以更容易地填充它:
var allRows = File
.ReadLines(@"C:'Users'Nate'Documents'Visual Studio 2015'Projects'Chapter 15'Chapter 15 Question 5'Chapter 15 Question 5'TextFile1.txt")
.Select(line => line.Split(unwanted).Select(int.Parse).ToList())
.ToList();
如果您对数组阵列满意,则无需执行任何操作:allRows
是包含矩阵的行和列的二维结构。
如果必须将其转换为二维数组,可以使用一对嵌套的for
循环:
if (allRows.Count == 0) {
// ... The file has no data - handle this error
}
var matrix = new int[allRows.Count, allRows[0].Count];
for (int row = 0 ; row != allRows.Count ; row++) {
for (int col = 0 ; col != allRows[0].Count ;col++) {
matrix[row, col] = allRows[row][col];
}
}