【问题标题】:Duplication of row while reading from file [duplicate]从文件读取时行重复[重复]
【发布时间】:2012-12-07 21:51:39
【问题描述】:

可能重复:
printing 2d array in c# through for loop

这就是我在 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];

请帮我解决这个问题!

【问题讨论】:

  • 如果您不喜欢或没有得到任何答案,您应该不只是重新发布相同的问题。对于初学者,您应该回答之前问题的 cmets 中向您提出的问题。
  • @L.B 而你却一直在发帖……
  • 你们可以忽略其余的,专注于这个问题吗?那就是问题所在!我仍然没有我的答案 =) 请先生,请在下面查看我的 cmets 的答案!

标签: c# file file-io multidimensional-array


【解决方案1】:

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

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

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

     Console.WriteLine(line);

【讨论】:

  • 主要问题不是印刷先生!连文件读取都没有正确完成!
  • Sodoku_Gri[i,j] = line[j];现在,当我更正你刚才提到的内容后,当我调用我的显示网格函数时,它只是一个 for 循环的集合来显示我的网格,我的输出都是“-”,除了二维网格中的 3-4 个位置
猜你喜欢
  • 2016-02-22
  • 2013-08-17
  • 1970-01-01
  • 2010-09-06
  • 2017-05-27
  • 2013-01-21
  • 1970-01-01
相关资源
最近更新 更多