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!

4
  • sorry the text file is a 4x4 array with spaces between them but it has come up as one line in the question: Commented Mar 13, 2014 at 18:01
  • ericlippert.com/2014/03/05/how-to-debug-small-programs Commented Mar 13, 2014 at 18:03
  • The lines are most probably separated by \r\n (carriage return / line feed). Commented Mar 13, 2014 at 18:12
  • Just tried the same and it works. Your lines are not exactly separated by \n rather \r\n Commented Mar 13, 2014 at 18:14

4 Answers 4

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]);
    }
}
Sign up to request clarification or add additional context in comments.

1 Comment

He should use ReadLines over ReadAllLines, given that he's only ever foreaching over it, for the sake of the reduced memory overhead.
1

Try ReadAllLines as opposed to ReadAllText

Comments

0

Replace any \r (carriage return)

input = input.Replace('\r',' ');

Comments

0

Replace your \r to "\r\n"

Try this:

foreach (var row in input.Split("\r\n"))

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.