0

I am programming in C# and I want to define an array which I don't know it's size, because I want to read somethings from file and I don't know the number of elements in that file. This is my code, and I have problem with "x" array!

using (TextReader reader = File.OpenText("Numbers.txt"))
{
    string[] bits;
    string text = reader.ReadLine();
    int i ,j=0;
    int [] x;
    while (text != null)
    {
        i = 0;
        bits = text.Split(' ');

        while (bits[i] != null)
        {
            x[j] = int.Parse(bits[i]);
            i++;
            j++;
        }

        text = reader.ReadLine();
    }

}

and after that I will get this error "Use of unassigned local variable 'x'" I don't know what should I do!! Please help me...

1
  • 3
    Use a List and when you have all the elements and know the size, convert to array. Commented Dec 18, 2013 at 21:13

5 Answers 5

7

You're getting that error because you did not initialize the variable (which you can't really do, unless you know the amount of items you will store in it).

Since you don't know the number of items, you should use a List instead, which can scale dynamically according to the number of items :

using (TextReader reader = File.OpenText("Numbers.txt"))
{
   string[] bits;
   string text = reader.ReadLine();
   int i;
   IList<int> x = new List<int>();
   while (text != null)
   {
      i = 0;
      bits = text.Split(' ');

      while (bits[i] != null)
      {
         x.Add(int.Parse(bits[i]));
         i++;
      }
      text = reader.ReadLine();
   }
}
Sign up to request clarification or add additional context in comments.

Comments

1

For a sweet one-liner:

int[] x = File
    .ReadAllLines("Numbers.txt")
    .SelectMany(s => s.Split(' ').Select(int.Parse))
    .ToArray();

For a low memory footprint, consider this alternative:

public static IEnumerable<int> ReadNumbers()
{
    using (var reader = new StreamReader(File.OpenRead("Numbers.txt."))) {
        string line;
        while ((line = reader.ReadLine()) != null) {
            foreach (var number in line.Split(' ')) {
                yield return int.Parse(number);
            }
        }
    }
}

Beware, every time you iterate over the result of ReadNumbers, the file will be read. Unless the numbers file is very large, the first solution is far superior.

1 Comment

I started to go there, but if it's a huge file, then you might consume more memory than desired. Fun, none the less. :)
0

The problem lies in this line:

int [] x;

Why don't you just make a simple list?

List<int> myIntList = new List<int>();

You can add items like:

myIntList.Add(1);

And later iterate through it like this:

foreach(int item in myIntList)
{
    Console.WriteLine(item);
}

Comments

0

As others have said, you need to use a list. In addition to what has been said, however, you should also be handling both IO errors as well as bad data as a best practice. This may be overkill for what you're doing, but best to get in this habit.

try
{
    List<int> x = new List<int>();
    using (TextReader reader = File.OpenText("Numbers.txt"))
    {
        string text;
        while ((text = reader.ReadLine()) != null)
        {
            string[] bits = text.Split(' ');
            foreach (string bit in bits)
            {
                // If you're parsing a huge file and it happens to have a
                // decent bit of bad data, TryParse is much faster
                int tmp;
                if(int.TryParse(bit, out tmp))
                    x.Add(tmp);
                else
                {
                    // Handle bad data
                }
            }
        }
    }
}
catch (Exception ex)
{
    // Log/handle bad text file or IO
}

Comments

0

Already some good answers here, but just for fun:

using (var reader = File.OpenText("Numbers.txt"))
{
    var x = new List<int>();
    var text = reader.ReadLine();
    while (text != null)
    {
        x.AddRange(text.Split(' ').Select(int.Parse));
        text = reader.ReadLine();
    }
}

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.