Cool Cat
Cool Cat

Reputation: 127

How to read numbers in a .txt file to an integer array?

I have a file that I need to save as an array. I am trying to convert a text file to an integer array using StreamReader. I just am unsure as to what to put in the for loop at the end of the code.

This is what I have so far:

//Global Variables
int[] Original;
//Load File
private void mnuLoad_Click_1(object sender, EventArgs e)
{
    //code to load the numbers from a file
    OpenFileDialog fd = new OpenFileDialog();

    //open the file dialog and check if a file was selected
    if (fd.ShowDialog() == DialogResult.OK)
    {
    //open file to read
    StreamReader sr = new StreamReader(fd.OpenFile());
    int Records = int.Parse(sr.ReadLine());

    //Assign Array Sizes
    Original = new int[Records];

    int[] OriginalArray;

    for (int i = 0; i < Records; i++)
    {
    //add code here
    }
}

The .txt file is:

    5
    6
    7
    9
    10
    2

PS I am a beginner, so my coding skills are very basic!

UPDATE: I have previous experience using Line.Split and then mapping file to arrays but obviously that does not apply here, so what do I do now?

//as continued for above code
for (int i = 0; i < Records; i++)
{
    int Line = int.Parse(sr.ReadLine());
    OriginalArray = int.Parse(Line.Split(';')); //get error here

    Original[i] = OriginalArray[0];
}

Upvotes: 0

Views: 9165

Answers (5)

Given Chansa
Given Chansa

Reputation: 1

//using linq & anonymous methods (via lambda)
string[] records = File.ReadAllLines(file);
int[] unsorted = Array.ConvertAll<string, int>(records, new Converter<string, int>(i => int.Parse(i)));

Upvotes: 0

Cjen1
Cjen1

Reputation: 1746

You should just be able to use similar code to what you had above it:

OriginalArray[i] = Convert.ToInt32(sr.ReadLine());

Every time the sr.ReadLine is called it increments the data pointer by 1 line, hence iterating through the array in the text file.

Upvotes: 3

ogrishmania
ogrishmania

Reputation: 29

Another way to do it if you'd like to read to the end of the file and you don't know how long it is with a while loop:

String line = String.Empty;
int i=0;
while((line = sr.ReadLine()) != null)
{
    yourArray[i] = Convert.ToInt32(line);
    i++;

    //but if you only want to write to the file w/o any other operation
    //you could just write w/o conversion or storing into an array
    sw.WriteLine(line); 
    //or sw.Write(line + " "); if you'd like to have it in one row
}

Upvotes: 0

d.moncada
d.moncada

Reputation: 17402

You can read the entire file into a string array, then parse (checking the integrity of each one).

Something like:

int[] Original;
//Load File
private void mnuLoad_Click_1(object sender, EventArgs e)
{
    //code to load the numbers from a file
    var fd = new OpenFileDialog();

    //open the file dialog and check if a file was selected
    if (fd.ShowDialog() == DialogResult.OK)
    {
        var file = fd.FileName;

        try
        {
            var ints = new List<int>();
            var data = File.ReadAllLines(file);

            foreach (var datum in data)
            {
                int value;
                if (Int32.TryParse(datum, out value))
                {
                    ints.Add(value);
                }
            }

            Original = ints.ToArray();

        }
        catch (IOException)
        {
            // blah, error
        }
    }
}

Upvotes: 0

Sherif Ahmed
Sherif Ahmed

Reputation: 1946

try this

OpenFileDialog fd = new OpenFileDialog();

if (fd.ShowDialog() == DialogResult.OK)
{
    StreamReader reader = new StreamReader(fd.OpenFile());

    var list = new List<int>();

    while (!reader.EndOfStream)
    {
        var line = reader.ReadLine();
        int value = 0;
        if (!string.IsNullOrWhiteSpace(line) && int.TryParse(line, out value))
            list.Add(value);
    }

    MessageBox.Show(list.Aggregate("", (x, y) => (string.IsNullOrWhiteSpace(x) ? "" : x + ", ") + y.ToString()));
}

Upvotes: 0

Related Questions