read each line of an input file and put it in a matrix in csharp

To read each line of an input file and put it in a matrix in C#, you can use the StreamReader class to read the file and then split each line into an array of strings. You can then assign each element of the array to the corresponding position in the matrix.

Here's an example:

main.cs
using System;
using System.IO;

// Create a 2D matrix
int numRows = 3;
int numCols = 4;
int[,] matrix = new int[numRows, numCols];

// Read the input file
using (StreamReader reader = new StreamReader("input.txt"))
{
    string line;
    int row = 0;

    // Read each line of the file
    while ((line = reader.ReadLine()) != null)
    {
        // Split the line into an array of strings
        string[] values = line.Split(' ');

        // Assign the values to the matrix
        for (int col = 0; col < numCols; col++)
        {
            matrix[row, col] = int.Parse(values[col]);
        }

        row++;
    }
}

// Print the matrix
for (int i = 0; i < numRows; i++)
{
    for (int j = 0; j < numCols; j++)
    {
        Console.Write(matrix[i, j] + " ");
    }

    Console.WriteLine();
}
802 chars
41 lines

In this example, we assume the input file has 3 rows and 4 columns, with each value separated by a space. Replace "input.txt" with the actual path to your input file. The resulting matrix will be printed to the console.

related categories

gistlibby LogSnag