【问题标题】:How to read from text file to array? [closed]如何从文本文件读取到数组? [关闭]
【发布时间】:2013-03-27 23:43:49
【问题描述】:

大家怎么了,

我的代码中有这个问题,我无法弄清楚如何从文本文件中读取并将其放入 c# 中的双类型数组 [1024,8] 的二维数组中。

0   148.9    19.4    20.2   112.6    41.9   205.7    46.7    87.2 
1    41.4    97.1    86.4   102.5    99.1   183.1    47.7    84.0
2   154.8   303.1   252.2   110.7    74.5    59.7   193.7   361.6 
.
.
1023    40.8   136.8   222.1    39.5   104.9    35.3    76.0   111.4 

我试图逐行读取这个文件,但这种方式对我没有帮助

static void Main(string[] args)
{
    int counter = 0;
    string line;
    double[] task = new double[8];
    // Read the file and display it line by line.
    System.IO.StreamReader file =
       new System.IO.StreamReader("c:\\test.txt");
    //int count = 0;
    while ((line = file.ReadLine()) != null && counter <= 1023)
    {
        //count++;
        //Console.WriteLine(count);

        string[] numbers = new string[8];
        int numCount = 0;
        for (int i = 0; i < line.Length; i++)
        {
            if (line[i] != ' ')
            {
                numbers[numCount] = "";
                while (line[i] != ' ')
                {
                    numbers[numCount] += line[i];
                    i++;
                }
                numCount++;
            }
        }
        for (int i = 0; i < 8; i++)
        {
            task[i] = Convert.ToDouble(numbers[i]);
        }
        counter++;
        Console.WriteLine("The array contain:");
        for (int i = 0; i < 8; i++)
            Console.WriteLine(task[i]);
    }
    file.Close();
    // Suspend the screen.
    Console.ReadLine();
}

【问题讨论】:

  • 您面临的问题是什么?到目前为止你尝试过什么?
  • 啊,你有密码!向我们展示您的尝试!
  • 使用TextReader.ReadLine然后将该行的值添加到数组中
  • I have this problem in my code 有什么问题,代码在哪里?
  • 你也不需要二维数组。你可以读取所有行并将它们拆分成一个列表你也可以使用linq来做到这一点,请解释为什么你需要将它放在一个二维数组中还有..

标签: c# arrays readfile


【解决方案1】:

您的代码看起来很整洁!从
for (int i = 0; i &lt; line.Length; i++) 替换您的代码并将其放置

int i=0;

    while (i < line.Length)
       {

            if (line[i] != ' ')
           {
               numbers[numCount] = "";
               while (line[i] != ' ')
               {

                   numbers[numCount] += line[i];
                   i++;
                   if (i >= line.Length) break;
               }
               numCount++;

           }
           i++;
       }
        for (int ui = 0; ui < 8; ui++)
       {
           task[ui] = Convert.ToDouble(numbers[ui]);
       }

       counter++;



       Console.WriteLine("The array contain:");
       for (int ui = 0; ui < 8; ui++)
           Console.WriteLine(task[ui]);

【讨论】:

  • 非常感谢,但是在二维数组中还有其他方法吗
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-07-07
  • 1970-01-01
  • 2015-01-28
相关资源
最近更新 更多