-3

可能重复:
通过for循环在c#中打印二维数组

这就是我在 txt 文件中的数据:

1--2--3--    
3-4-4-5--    
-7-3-4---
7--5--3-6    
--7---4--    
3-2--4-5-    
------3--    
2-6---7---    
4---4---3-

之间没有任何空行!上面有这个格式问题!

是我的 c# 代码也可以通过显示器进行文件读取:

public void populate_grid_by_file()
        {
            int counter = 0;
            string line;

            // Read the file and display it line by line.
            System.IO.StreamReader file =
               new System.IO.StreamReader("data.txt");
            for (int i = 0; i < Sodoku_Gri.GetLength(0); i++)
            {
                while ((line = file.ReadLine()) != null)
                {
                    for (int j = 0; j < Sodoku_Gri.GetLength(1); j++)
                    {
                        Sodoku_Gri[i,j] = line[j];
                        Console.Write(line[j].ToString());

                    }
                    Console.WriteLine(line);
                    counter++;
                }
            }
            file.Close();
            // Suspend the screen.
            Console.ReadLine();
        }   

但是当我用上面的文件显示我的数组时,它就像:

1--2--3--1--2--3--    
3-4-4-5--3-4-4-5--    
-7-3-4----7-3-4---    
7--5--3-67--5--3-6    
--7---4----7---4--    
3-2--4-5-3-2--4-5-    
------3--------3--    
2-6--7---2-6--7---    
4---4---3-4---4---3-

cnt明白为什么重复!帮助!

调试的时候发现线路有问题:

Console.Write(line[j].ToString());

这意味着这里的元素不会自动加载到数组中:

Sodoku_Gri[i,j] = line[j];

请帮我解决这个问题!

4

1 回答 1

3

您在此处逐个字符地显示该行一次:

    Console.Write(line[j].ToString());

然后在这里一次完成整行:

     Console.WriteLine(line);
于 2012-12-07T21:55:13.967 回答