1

I have been using this link as an example, but have been having troubles with it: 2d Array from text file c#

I have a textfile that contains :

1 1 0 0
1 1 1 0
0 0 0 1
0 1 0 0

And I'm trying to use the function:

static void Training_Pattern_Coords()
{
    String input = File.ReadAllText(@"C:\Left.txt");

    int i = 0, j = 0;
    int[,] result = new int[4, 4];
    foreach (var row in input.Split('\n'))
    {
        j = 0;
        foreach (var col in row.Trim().Split(' '))
        {
            result[i, j] = int.Parse(col.Trim());
            j++;
        }
        i++;      
    }
    Console.WriteLine(result[1, 3]);

    Console.ReadLine();
}

However I keep getting the error message (Input String was not in correct format) at the line :

foreach (var row in input.Split('\n'))

I think it has something to do with the spaces within the textfile but I'm not entirely sure. Thanks for your help!

Community
  • 1
  • 1

4 Answers4

2

Instead of File.ReadAllText use File.ReadLines.By doing that you won't need to use Split('\n').

int[,] result = new int[4, 4];

var lines = File.ReadLines(@"C:\Left.txt")
               .Select(x => x.Split()).ToList();
for (int i = 0; i < 4; i++)
{
    for (int j = 0; j < 4; j++)
    {
        result[i, j] = int.Parse(lines[i][j]);
    }
}
Selman Genç
  • 100,147
  • 13
  • 119
  • 184
  • 1
    He should use `ReadLines` over `ReadAllLines`, given that he's only ever `foreach`ing over it, for the sake of the reduced memory overhead. – Servy Mar 13 '14 at 18:05
1

Try ReadAllLines as opposed to ReadAllText

MrM
  • 21,709
  • 30
  • 113
  • 139
0

Replace any \r (carriage return)

input = input.Replace('\r',' ');
Rahul
  • 76,197
  • 13
  • 71
  • 125
0

Replace your \r to "\r\n"

Try this:

foreach (var row in input.Split("\r\n"))
f.fujihara
  • 101
  • 1