尝试将int从文件加载到2d数组中,收到“输入字符串格式不正确”错误

我一直在尝试完成C#中的游戏设计课程的分配,我遇到的问题之一是无法使用所有加载信息加载Save1.GAME文本文件,我收到了“系统.FormatException:“输入字符串的格式不正确。”“错误。

目前,此任务包括一个小面板,玩家在其中设计了一个推箱子(https://en.wikipedia.org/wiki/Sokoban)地图,我已经完成了这一部分,现在我必须将该保存文件加载到程序中,然后生成“小块”(图块只是其中的小方块)进入实际将要玩游戏的面板。

到目前为止,我已经尝试加载文件并将其逐行写入字符串数组。 我也尝试将整个文件写入字符串并使用.split(',')函数,但无济于事。 我已经尝试了很多想法,老实说我已经忘记了其中的每一个。


我将在其中玩游戏的表单上的加载按钮:

private void loadToolStripMenuItem_Click(object sender,EventArgs e)
        {
            OpenFileDialog openLevelDialog = new OpenFileDialog();
            openLevelDialog.Title = "Select level to load";



            if (openLevelDialog.ShowDialog() == DialogResult.OK)
            {

                string MyString = System.IO.File.ReadAllText(openLevelDialog.FileName);


                int i = 0;
                int j = 0;

                //My array where I will just dump the whole file into.
                int[,] result = new int[10,10];

                //foreach loop where I attempt to go line-by-line and split the individual numbers by ','
                foreach (var row in MyString.Split('\n'))
                {
                    j = 0;
                    foreach (var col in row.Trim().Split(','))
                    {
                        result[i,j] = int.Parse(col.Trim()); //Exception happens here.
                        j++;
                    }
                    i++;
                }

                //Just an attempt to display what the variable values in my form,ignore this part.
                for (int a = 0; a < result.GetLength(0); a++)
                {
                    for (int w = 0; w < result.GetLength(1); w++)
                    {
                        label1.Text += result[a,w].ToString();
                    }
                }  
            }
        }

这是Game1.GAME文件

2,2

0,0

0,1,1

1,2

1,3

注意:有第四个枚举,其值为“目标”,但在此特定映射中,我没有添加任何枚举。

通常的外观

2,2
0,0
0,1
1,2
1,3

我希望它只是加载字符串,将其切成int数组,但是无论我做什么,我似乎都无法越过异常。

谢谢您的时间。


Here's my file from inside notepad++

My System.IO return

hhyyoo 回答:尝试将int从文件加载到2d数组中,收到“输入字符串格式不正确”错误

根据您提供的信息,您在最后一行出错了,因为换行符位于最后一条记录的末尾。

一种解决方法是检查迭代中rowNullEmptyWhitespace,还是循环continue(如果有这种情况)是true

foreach (var row in MyString.Split('\n')) 
{
   //skip iteration if row is null,empty,or whitespace
   if (string.IsNullOrWhitespace(row))
      continue;
本文链接:https://www.f2er.com/3169613.html

大家都在问