0

This is driving me literally insane for some reason my code to read a simple text file of ints into an int array wont work.

private void HardButton_Click(object sender, EventArgs e)
    {
        int[] hard1 = { };
        int counter = 0;


        using (StreamReader inFile = new StreamReader("h1.txt"))
        {
            string str = null;

            while ((str = inFile.ReadLine()) != null)
            {
                hard1[counter] = Convert.ToInt32(str);
                counter++;
            }
        }

hard1 is an array of ints that i need to hold each integer placed into it by reading the text file. My error is that my array is out of bounds even though I'm iterating each time through the loop. I am at a loss.

EDIT: Here is the txt file input

0502090
6070203
0502010
5020101
0503010
4020905
0608070

7582391
6478283
8592914
5628191
6573812
4728915
3648271
4
  • You probably of more than one number on a line like : "1 2 3 4 5". So you need to split the numbers on the line to an array. Commented Apr 3, 2019 at 16:46
  • 2
    Do you understand what int[] hard1 = { }; does? i.e. what is the length of hard1? Commented Apr 3, 2019 at 17:01
  • 2
    Your array does not have a size. See learn.microsoft.com/en-us/dotnet/csharp/programming-guide/… Commented Apr 3, 2019 at 17:04
  • Edited my original question to include input Commented Apr 3, 2019 at 18:02

3 Answers 3

4

C#/.Net has real arrays, not the psuedo-array collections you see in so many other languages (it has those, too, it just doesn't try to pass them off as arrays). One attribute of real arrays is a fixed size.

So when you declare the array like this:

int[] hard1 = { };

what you have is an array fixed at size 0, and therefore assigning to the array later on like this:

hard1[counter] = Convert.ToInt32(str);

is assigning to nowhere.

You have many options to fix this. Here is one of them:

private void HardButton_Click(object sender, EventArgs e)
{
    var result = File.ReadLines("h1.txt").
         Where(line => !string.IsNullOrWhitespace(line)).
         Select(line => int.Parse(line)).
         ToArray();
}
Sign up to request clarification or add additional context in comments.

2 Comments

Still got the same error: "input string was not in the correct format"
That's not same error. The old error was "Index was outside the bounds of the array." But I added a fix.
1

If you don't know the length in advance... use a list.

private void HardButton_Click(object sender, EventArgs e)
{
    var hard1 = new List<int>();
    int counter = 0;


    using (StreamReader inFile = new StreamReader("h1.txt"))
    {
        string str = null;

        while ((str = inFile.ReadLine()) != null)
        {
            hard1.Add(Convert.ToInt32(str));
            counter++;
        }
    }
...

If you don't have complete control over the file it might be necessary to do extra controls before converting to int as well.

  • Is every line exactly one integer?
  • Do I need to trim?
  • Can there be empty lines?

Comments

0

Use this:

private void button1_Click(object sender, EventArgs e)
{
    int[] hard1 = { };

    var lines = File.ReadAllLines("h1.txt");
    var lineWithoutEmptySpace = lines.Where(x => !string.IsNullOrEmpty(x)).ToArray();
    hard1 = new Int32[lineWithoutEmptySpace.Length];

    for (var i = 0; i < lineWithoutEmptySpace.Length; i++)
    {
        hard1[i] = Convert.ToInt32(lineWithoutEmptySpace[i]);
    }
}

3 Comments

This will work, but it's still very wasteful code: the = { } creates a new empty object that will be immediately thrown away; ReadAlllLines() vs ReadLines() forces the entire file into an array in memory at the same time, even though that array will be discarded almost immediately and the .Where() method works just as well with ReadLines()
Worked almost perfectly but is there anyway to keep leading zeroes in my text file. Im assuming that they are being removed because of the !string.isNullorEmpty. Anyway to fix that?
No integer has a 0 at the beginning, when you convert string "0502010" to int, it become: 502010. See this post: stackoverflow.com/questions/6615454/…

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.