SiRaZz
SiRaZz

Reputation: 43

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.

Upvotes: 0

Views: 1161

Answers (4)

Jodrell
Jodrell

Reputation: 35716

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

Upvotes: 2

SiRaZz
SiRaZz

Reputation: 43

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++;

Upvotes: 0

neleus
neleus

Reputation: 2280

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

Upvotes: 0

James Gaunt
James Gaunt

Reputation: 14783

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

Upvotes: 2

Related Questions