0

我正在尝试将文本文件读入二维数组。但是我得到一个错误

输入字符串的格式不正确。

我检查了文本文件,一切正常,但我不明白为什么会发生这个错误?

        int[,] numberMatrix = new int[10, 10];
        string[] split = null;

        for (int rowCount = 1; rowCount < 11; rowCount++)
        {
            int[] temp1DArray = new int[10];
            string fileLocation = "C:\\Week10\\one.txt";
            string textFile = File.ReadAllText(fileLocation);

            for (int columnCount = 1; columnCount < 11; columnCount++)
            {
                string delimStr = " ";
                char[] delimiter = delimStr.ToCharArray();
                //string fileLocation = "C:\\Week10\\1-100.txt";
                //string textFile = File.ReadAllLines(fileLocation);
                for (int x = 0; x <= 10; x++)
                {
                    split = textFile.Split(delimiter, x);
                }
            }

            for (int rowCount1 = 1; rowCount1 < 11; rowCount1++)
            {
                for (int columnCount = 1; columnCount < 11; columnCount++)
                {
                    numberMatrix[rowCount1 - 1, columnCount - 1]   =Convert.ToInt32(split.ElementAt(columnCount - 1));
                }
            }
        }

        for (int rowCount = 10; rowCount > 0; rowCount--)
        {
            for (int columnCount = 10; columnCount > 0; columnCount--)
            {
                Console.WriteLine(numberMatrix[rowCount - 1, columnCount - 1]);
            }
        }
    }
4

2 回答 2

0

好吧,您还没有提供任何文件内容和确切的异常描述(它可以以任何可能的原因触发)。我可以为文件解析提供更简单的实现。我想不出答案,它会神奇地找到为什么文件中的一个数字无法解析为的原因int

string[] lines = File.ReadAllLines(@"C:\temp\1.txt");
var options = StringSplitOptions.RemoveEmptyEntries;

int[][] numbers = lines.Select(line => line.Split(new[]{' '}, options)
                                           .Select(int.Parse)
                                           .ToArray())
                       .ToArray();

Console.WriteLine(string.Join(Environment.NewLine, 
                              numbers.Select(n => string.Join(" ", n))));

对于文件:

1 10 20 30 
4234 35 123 543
42 54 345 645

印刷:

1 10 20 30
4234 35 123 543
42 54 345 645

如果您需要矩形数组,请int[,]使用下一个代码将其解析为。

int [,] numbersRect = new int[numbers.Length, numbers[0].Length];

for (int i = 0; i < numbersRect.GetLength(0); i++)
{
    for (int j = 0; j < numbersRect.GetLength(1); j++)
    {
        numbersRect[i,j] = numbers[i][j];
    }
}
于 2013-04-01T11:32:37.113 回答
-1

从我站立的地方 split 返回一个数组。numberMatrix[rowCount1 - 1, columnCount - 1] 是数组元素 - 不是数组本身。所以 numberMatrix[rowCount1 - 1, columnCount - 1] =Convert.ToInt32(split.ElementAt(columnCount - 1)); 将触发异常。Convert.ToInt32 也采用单个值而不是数组。

于 2013-04-01T11:43:12.153 回答