Reputation: 57
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
Upvotes: 0
Views: 74
Reputation: 189
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]);
}
}
Upvotes: 0
Reputation: 415600
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();
}
Upvotes: 4
Reputation: 976
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.
Upvotes: 1