对于Int32类型,值要么太大要么太小.读取和解析文本文件

本文关键字:和解 读取 文本 文件 类型 Int32 对于 | 更新日期: 2023-09-27 18:07:49

我一直无法应用任何解决方案来解决这个问题。异常发生在这一行:currentMap[row, col] = Int32.Parse(s);我要做的是将一个特定的文件传递给这个方法,该文件存储的行数如下所示:

1,1,1
1,0,1
1,1,1

然后我想要每个数字存储在int[,] currentMap返回。我正在使用的文件不包含大数。我认为我创建的数组的大小是正确的,所以我不明白为什么这不起作用。我习惯在java中使用NextInt做类似的事情,但我找不到c#的替代方案。

谢谢你的帮助。

private int[,] LoadMapArray(String filename)
    {
        int[,] currentMap;
        int rows = 0;
        int cols = 0;
        StreamReader sizeReader = new StreamReader(filename);
        using (var reader = File.OpenText(filename))
        {
            while (reader.ReadLine() != null)
            {
                string line = sizeReader.ReadLine();
                cols = line.Length;
                rows++;
            }
        }
        currentMap = new int[rows,cols];
        StreamReader sr = new StreamReader(filename);
        for (int row = 0; row < rows + 1; row++)
        {
            string line = sr.ReadLine();
            string[] split = new string[] {","};
            string[] result;
            result = line.Split(split, StringSplitOptions.None);
            int col = 0;
            foreach (string s in result)
            {
                currentMap[row, col] = Int32.Parse(s);
                col++;
            }
        }
        return currentMap;
    }

编辑:代码在改变我访问文件的方式后被修复。然后我必须修改它来捕获null:

for (int row = 0; row < rows + 1; row++)
        {
            string line = sr.ReadLine();
            string[] split = new string[] { "," };
            string[] result;
            if (line != null)
            {
                result = line.Split(split, StringSplitOptions.None);
                int col = 0;
                foreach (string s in result)
                {
                    currentMap[row, col] = Int32.Parse(s);
                    col++;
                }
            }

        }

对于Int32类型,值要么太大要么太小.读取和解析文本文件

不,数组的大小不正确。在每个循环中读取两行,但只增加一次行计数器。

    using (var reader = File.OpenText(filename))
    {
        string line = string.Empty;
        while ((line = reader.ReadLine()) != null)
        {
            rows++;
        }
    }

我确信cols计数也不正确,但它不会引发异常,因为你的cols维度比需要的大。(包括逗号空格,而不仅仅是数字)

一个更简单的方法(如果你的文件不是很大)是使用file . readalllines ()

string[] split = new string[] {","};
string[] lines = File.ReadAllLines(filename);
int rows = lines.Length;
int cols = lines[0].Split(split, StringSplitOptions.RemoveEmptyEntries).Count();
currentMap = new int[rows,cols];
for (int row = 0; row < rows; row++)
{
      string line = lines(row);
      string[] result = line.Split(split, StringSplitOptions.None);
      int col = 0;
      foreach (string s in result)
      {
           int value;
           Int32.TryParse(s, out value)
           currentMap[row, col] = value;
           col++;
      }
 }

现在,整个文件都在内存中,只需一个磁盘操作,您可以使用内存中的字符串。整数的解析应该改为使用Int32。在检索值不是有效整数的情况下,尝试解析以避免异常。