【发布时间】:2016-04-20 12:07:32
【问题描述】:
大家好,我试图从文本文件中保存一个数组,但我正在努力弄清楚如何保存它。从文本文件中可以看出,我可以打印矩阵的所有元素。
示例输入:
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++;
}
}
}
}
【问题讨论】:
-
您的代码只是从文件中读取,并没有保存任何内容...? IE。你需要一个
StreamWriter或类似的东西来写一个文件。 (msdn.microsoft.com/en-us/library/… ) 但是,我真的不明白您为什么要从文件中读取某些内容只是为了再次保存它。 -
哪里抛出的错误?