如何从文本文件读取到数组? [英] How to read from text file to array?

查看:105
本文介绍了如何从文本文件读取到数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家最近怎么样,

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

I have this problem in my code and I couldn't figure out how to read from text file and put it in 2-dimension array of double type array [1024,8] in c# .

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 

<小时>

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


I tried to read this file line by line, but this way didn't help me

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();
}

推荐答案

你的代码看起来很整洁!替换
for (int i = 0; i < 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]);

这篇关于如何从文本文件读取到数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆