JeremyM
JeremyM

Reputation: 11

Storing contents of text file into a char[,] array

I am trying to get a coordinate system where adjusting the x and y values would determine where to output my char. For example, if my text file had the content:

1 2 3

4 5 6

7 8 9

When I output array[2,3] = "X", i would get

1 2 3

4 5 6

7 X 9

Currently, my array only stores the first row of the contents of a txt. I want it to display the values 1 to 9 from the text. My codes:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;

namespace ConsoleApp2Test
{

public class Program

{
    public int xLocation;
    public int yLocation;

    public static void Main()
    {
        int counter = 0;
        string directory = System.IO.Directory.GetParent(System.IO.Directory.GetParent(Environment.CurrentDirectory).ToString()).ToString();
        directory += @"/Maps/Level1.txt";
        char[,] array1 = new char[3, 3];

        for (int i = 0; i < array1.GetLength(0); i++)
        {
            for (int j = 0; j< array1.GetLength(1); j++)
            {
                array1[i, j] = (Char)File.ReadAllBytes(directory)[counter];
                Console.Write(array1[i, j]);
                ++counter;
            }               
        }          
    }

}
}

Am I doing it all wrong?

Upvotes: 0

Views: 2847

Answers (1)

Link
Link

Reputation: 1711

Ok it seems like your text is has more character than your text file. You are iterating over every element of your 3x3 array1, but your text file has 11 characters (the blanks count as well).

Here is a dynamic (but very naive) approch:

  1. Read the content of the file with ReadAllText instead of ReadAllBytes
  2. Split the array by the blank sign
  3. Iterate through every sign and put it in your map

Source:

public static void Main()
{
    string directory = System.IO.Directory.GetParent(System.IO.Directory.GetParent(Environment.CurrentDirectory).ToString()).ToString();
    directory = Path.Combine(directory, @"/Maps/Level1.txt"); // Better use Path.Combine for combining paths

    // It is enough to read the text once and not on every iteration
    string fileContent = File.ReadAllText(directory);

    // In your provided sample the blank sign signals a new row in the matrix
    string[] rows = fileContent.Split(' ');

    // Assuming that it is a matrix, which must always be the same width per line
    // NullChecks ...
    int rowLength = rows[0].Length;
    int rowCount = rows.Length;
    char[,] map = new char[rowLength, rowCount];

    for (int i = 0; i < rowCount; i++)
    {
        for(int j = 0; j < rowLength; j++)
        {
            map[i, j] = rows[i][j];
            Console.Write(map[i, j]);
        }
        // We are done with this row, so jump to the next line
        Console.WriteLine();
    }
}

Upvotes: 1

Related Questions