0

I have a file containing numbers of two digits.

10
20 25
30 45 60

I am reading the file line by line as strings and converting them into a string array. Then, I am trying to insert them in an integer two dimensional list using int.Parse() method but it's throwing an "Index out of range" exception.

What am I doing wrong?

public List<List<int>> num = new List<List<int>>();

int row = 0;      
System.IO.StreamReader file = new System.IO.StreamReader("D:\\data.txt");
while (!file.EndOfStream)
{
   string line = file.ReadLine();
   string[] str = line.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);

   for (int i = 0; i < str.Length; i++)
   {
      num[row].Add(int.Parse(str[i]));
   }
   row++;
}
  • 5
    If you're getting `IndexOutOfRange` it sounds to me like you're not having a problem with `Int.Parse` but rather `str` doesn't contain what you think it does. Set a breakpoint and step through it; make sure it has the data you think it does and that `i` is also valid. Also, use `TryParse(string s, out int result)` instead. – sab669 Oct 23 '15 at 15:21
  • Should be pretty simple to step through this line by line ans see what is happening (i.e. what is at `str[i]`). – crashmstr Oct 23 '15 at 15:21
  • Please post a short but complete program demonstrating the problem, with input, expected output, and actual output - including the full stack trace in this case. – Jon Skeet Oct 23 '15 at 15:24
  • The code snippet has been changed, expected output is just as mentioned in the description. – Bashiul Alam Sabab Oct 23 '15 at 16:10
  • You're getting `IndexOutOfRange` because you're subscripting into `num` which is a list of lists.... but since you never add any lists to the outer list you can't grab `num[0]`. There's nothing there. – Jeff B Oct 23 '15 at 20:33

0 Answers0