Rahul Sharma
Rahul Sharma

Reputation: 8311

How to store a line from a textfile into an array of fixed size

So, I have this scenario where I am reading from a file which has a structure like this:

4
4 8 2 1
2 4 6 3
3 6 9 2
1 3 2 8

Where 4 in the first line is the size of the matrix that will be generated. The lines below are the matrix values which will always be a multi dimensional matrix of size [4,4] means that it will have 4 rows and 4 columns.

How can I store in this in a data structure and access the elements for performing calculations?

My current code:

class Program
{
    static void Main(string[] args)
    {
        var fileName = "sampleinput.txt";
        int T = Convert.ToInt32(File.ReadLines(fileName).First()); // gets the first line from file.
        var lines = File.ReadLines(fileName).Skip(1).Take(T);
        int[,] array1 = new int[T, T];
        foreach(var line in lines)
        {

            Console.WriteLine(line);
            //How to store the values here in a multidimensional array and access the values as required?
        }

    }
}

Upvotes: 1

Views: 88

Answers (2)

Owuor
Owuor

Reputation: 616

Try this out:

class Program
{
static void Main(string[] args)
{
    var fileName = "sampleinput.txt";
    int T = Convert.ToInt32(File.ReadLines(fileName).First()); // gets the first line from file.
    var lines = File.ReadLines(fileName).Skip(1).Take(T);
    int[,] array1 = new int[T, T];
    var n = 0
    foreach(var line in lines)
    {
       var j = 0; 
       foreach(var i in line.Split().Select(s => int.Parse(s))) 
       { 
        array1 [n, j] = i;
        j++; 
       }
      n++;
    }

}
}

Upvotes: 1

Osama Khalid
Osama Khalid

Reputation: 66

This seems like you are learning how to manipulate strings and how to use data structures. In foreach loop you are getting one line from file in variable line. So you can split this string then store into a string array and then start a new loop inside your foreach loop which iterates through this string array and assign the values to your multi dimensional array like this:

 class Program
{
    static void Main(string[] args)
    {
        var fileName = "sampleinput.txt";
        int T = Convert.ToInt32(File.ReadLines(fileName).First()); // gets the first line from file.
        var lines = File.ReadLines(fileName).Skip(1).Take(T);
        int[,] array1 = new int[T, T];
        foreach(var line in lines)
        {
            string[] lineElements = line.Split(" ");
            int j=0;
            for(int i=0;i<lineElements.Length;i++)
            {
               array1[j,i] = Convert.ToInt32(lineElements[i]);
            }
            j++;
        }

    }
}

Upvotes: 0

Related Questions