简体   繁体   中英

C# Need help to read text file to 2D or jagged array

I'am working with SMACOF algorythm and have a little problem. I'am trying to read text file wich contains elements like this:

5.1 3.5 1.4 0.2 
4.9 3.0 1.4 0.2 
4.7 3.2 1.3 0.2 
4.6 3.1 1.5 0.2

Where are few hundred lines of these elements. So far I have managed to read just first line and don't know why it's not reading all lines. Here is my code:

    static void Main(string[] args)
    {
        string[] lines = File.ReadAllLines("duom.txt");
        string[][] grid = new string[lines.Length][];
        for (int i = 0; i < lines.Length; i++)
        {
            grid[i] = lines[i].Split(',');
        }
        for (int i = 0; i < lines.Length; i++)
        {
            for (int j = 0; j < lines[i].Length; j++)
            {
                Console.WriteLine(grid[i][j]);
                Console.ReadLine();
            }
        }
    }

So, maybe you guys can explain what is wrong with my code, and how propely read text file? Thanks.

Your second loop will go out of bounds as your looping over the length of the line (in characters) not the length of the array in grid[i].

    static void Main(string[] args)
    {
        string[] lines = File.ReadAllLines("duom.txt");
        string[][] grid = new string[lines.Length][];
        for (int i = 0; i < lines.Length; i++)
        {
            grid[i] = lines[i].Split(',');
        }
        for (int i = 0; i < lines.Length; i++)
        {
            for (int j = 0; j < **grid**[i].Length; j++)
            {
                Console.WriteLine(grid[i][j]);
                Console.ReadLine();
            }
        }
    }

Wouldn't the code below suffice, its shorter and prevents copying the whole file into memory before transforming to an array.

var grid  = File.ReadLines("duom.txt")
    .Select(line => line.Split(' ').Select(item => double.Parse).ToArray())
    .ToArray();

foreach(var item in grid.SelectMany(row => row))
{
    Console.WriteLine(item);
}

Maybe I'm missing something but this Split(',') looks shady. I dont see ',' in your example. Try Split(' ') instead!

Thanks everyone for help, but I managed to fix by myself, here is solution:

int h = 0;
        int g = 0;
        string linijos = File.ReadAllText("duom.txt");
        double[][] nuskait = new double[150][];
        foreach (var row in linijos.Split('\n'))
        {
            h = 0;
            nuskait[g] = new double[4];
            foreach (var col in row.Trim().Split(' '))
            {
                nuskait[g][h] = double.Parse(col);
                h++;
            }
        }
        g++;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM