#1
  1. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Nov 2008
    Posts
    10
    Rep Power
    0

    Parallel array from file using C#


    Hello all, I'm trying to take a text file with names and grades, place it into an array, then use the array to make some displays, modify it, ect. I can do the rest, but I'm just entirely out of ideas how to formulate the arrays.

    Code:
    Text file: grades.txt
    
    Casey Weaver|80|100|95
    John Trump|75|80|85
    (eight more random names and sets of 3 grades)
    The array size only needs to be set when the program runs to fill the lines. The deal is I need 4 arrays, one for each set.

    The plan is to first pull it all into one single array using .Split.

    Code:
                string input;
    
                using (StreamReader inputFile = new StreamReader("grades.txt"))
                {
                    while ((input = inputFile.ReadLine()) != null)
                    {
                        string[] test = input.Split('|');
                        foreach (string i in test)
                        {
                            Console.WriteLine(i);
                        }
                    }
                }
    But now how do I fill my four main arrays with the results?

    namesArray
    grade1Array
    grade2Array
    grade3Array

    namesArray is a string, the rest are ints, but if it's better, I'll just make all the arrays strings, and parse the ints I need at a later time.

    The arrays must be parallel. Any help? I'm pretty sure it's gotta be simple, I'm just not seeing it.
  2. #2
  3. Devshed God 1st Plane (5500 - 5999 posts)

    Join Date
    Jun 2005
    Posts
    5,964
    Rep Power
    4852
    If you have it all in one array then you could just split it up based on index mod 4. Personally, I'd shuck the arrays and use a class with an instantiation for each person in the file.
    Write no code whose complexity leaves you wondering what the hell you did.
    Politically Incorrect DaWei on Pointers Grumpy on Exceptions
  4. #3
  5. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Nov 2008
    Posts
    10
    Rep Power
    0
    Originally Posted by sizablegrin
    If you have it all in one array then you could just split it up based on index mod 4. Personally, I'd shuck the arrays and use a class with an instantiation for each person in the file.
    I need the arrays for the future work with the program.

    I could use a for loop that's taking the indexes of the array, maybe divisible by 4.

    Code:
    int j
    j = test.Length / 4
    
    for(i ; i < j ; i=i+3)
    but then..how to get each one of those 4 that it outputs each time in that cycle into the seperate arrays....Gah this is confusing. :mad:
  6. #4
  7. Devshed God 1st Plane (5500 - 5999 posts)

    Join Date
    Jun 2005
    Posts
    5,964
    Rep Power
    4852
    Errrrr...see again my comment regarding mod 4.
    Write no code whose complexity leaves you wondering what the hell you did.
    Politically Incorrect DaWei on Pointers Grumpy on Exceptions
  8. #5
  9. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Nov 2008
    Posts
    10
    Rep Power
    0
    Originally Posted by sizablegrin
    Errrrr...see again my comment regarding mod 4.
    Do you have an example? I've never heard what you're talking about. Do you mean splitting the indexes by modulus 4? How would that take my 0,1,2,3 each time and put them in name, g1, g2, and g3 respectively?

    Yes I'm a dunce. :cadrunk:
  10. #6
  11. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Nov 2008
    Posts
    10
    Rep Power
    0

    Cool Got it!


    Code:
    //Casey Weaver
    //C12P7
    //Student Average Calculator
    
    using System;
    using System.Collections;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Data;
    using System.Drawing;
    using System.Text;
    using System.Windows.Forms;
    using System.IO;
    
    namespace C12P7
    {
        public partial class Form1 : Form
        {
            public Form1()
            {
                InitializeComponent();
            }
    
            private void Form1_Load(object sender, EventArgs e)
            {
                string input;
    
                string[] test = new string[4];
                ArrayList name = new ArrayList();
                ArrayList grade1 = new ArrayList();
                ArrayList grade2 = new ArrayList();
                ArrayList grade3 = new ArrayList();
    
                using (StreamReader inputFile = new StreamReader("students.txt"))
                {
                    try
                    { 
                        while ((input = inputFile.ReadLine()) != null)
                        {
                            test = input.Split('|');
    
                            name.Add(test[0]);
                            grade1.Add(test[1]);
                            grade2.Add(test[2]);
                            grade3.Add(test[3]);
                        }
                    } 
    
                    catch (FileNotFoundException exc)
                    {
                        MessageBox.Show("File Not Found !\n" + exc.Message); ;
                    }
    
                    catch (Exception exc)
                    {
                        MessageBox.Show(exc.Message);
                    }
                    inputFile.Close();
                }
                using (StreamWriter averages = new StreamWriter("averages.txt"))
                {
                    try
                    {
                        for (int x=0; x < name.Count; x++)
                        {
                            double averageGrade;
                            averageGrade = (double.Parse(grade1[x].ToString()) + double.Parse(grade2[x].ToString()) + double.Parse(grade3[x].ToString())) / 3;
                            averages.WriteLine("{0} has an average of {1:F2}.", name[x], averageGrade);
                        }
                    }
                    catch (System.ArithmeticException arithmetic)
                    {
                        MessageBox.Show(arithmetic.Message);
                    }
    
                    try
                    {
                        averages.Close();
                        File.Exists("averages.txt");
                    }
                    catch (System.IO.IOException nofile)
                    {
                        txtsuccess.Text = nofile.Message;
                    }
                    txtsuccess.Text = "Congratulations, File has been successfully written!";
                    txtsuccess.Visible = true;
                }
            }
        }
    }
  12. #7
  13. ASP.Net MVP
    Devshed Specialist (4000 - 4499 posts)

    Join Date
    Aug 2003
    Location
    WI
    Posts
    4,378
    Rep Power
    1510
    This should work even better:
    Code:
    public class Student
    {
        public string name { get; set; }
        public double grade1 { get; set; }
        public double grade2 { get; set; }
        public double grade3 { get; set; }
    
        public Student (string name, double grade1, double grade2, double grade3)
        {
            this.name = name;
            this.grade1 = grade1;
            this.grade2 = grade2;
            this.grade3 = grade3;
        }
    }
    
    private List<Student> students;
    
    private List<Student> ReadStudents(string fileName)
    {
        string input;
        string[] values;
        var result = new List<Student>();
        using (var inputFile = new StreamReader(fileName))
        {
            while ((input = inputFile.ReadLine()) != null)
            {
                values = input.Split('|');
                result.Add(new Student(values[0], 
                           Convert.ToDouble(values[1]),
                           Convert.ToDouble(values[2]),
                           Convert.ToDouble(values[3]) ));
            }
        }
        return result;
    }
    
    private void WriteAverages(string fileName, List<Student> students)
    {
        using (var averages = new StreamWriter("averages.txt"))
        {
            foreach (Student student in students)
            {
                double averageGrade = (student.grade1 + student.grade2 + student.grade3)/3;
                averages.WriteLine("{0} has an average of {1:F2}.", student.name, averageGrade);
            }
        }
    }
    
    private void Form1_Load(object sender, EventArgs e)
    {
        try
        {
            students = ReadStudents("students.txt");
        }
        catch (FileNotFoundException exc)
        {
            MessageBox.Show("File Not Found !\n" + exc.Message); ;
            return;
        }
        catch (Exception exc)
        {
            MessageBox.Show(exc.Message);
            return;
        }
    
        try
        {
            WriteAverages("averages.txt");
        }
        catch (Exception exc)
        {
            MessageBox.Show(exc.Message);
            return;
        }
    
        txtsuccess.Text = "Congratulations, File has been successfully written!";
        txtsuccess.Visible = true;
    }
    Last edited by f'lar; April 23rd, 2009 at 08:27 AM.
    Primary Forum: .Net Development
    Holy cow, I'm now an ASP.Net MVP!

    [Moving to ASP.Net] | [.Net Dos and Don't for VB6 Programmers]

    http://twitter.com/jcoehoorn
  14. #8
  15. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Aug 2013
    Posts
    4
    Rep Power
    0
    The best way now with .Net >=4 is to parallel process the arrays once you have them.

    Example:

    Code:
    AllLines = new string[MAX]; //only allocate memory here
    using (StreamReader sr = File.OpenText(fileName))
    {
    	int x = 0;
    	while (!sr.EndOfStream)
    	{
    		AllLines[x] = sr.ReadLine();
    		x += 1;
    	}
    } //CLOSE THE FILE because we are now DONE with it.
    Parallel.For(0, AllLines.Length, x =>
    {
    	DoStuff(AllLines[x]);
    });
    Reference:


    http://blogs.davelozinski.com/curiou...ess-text-files

    _

IMN logo majestic logo threadwatch logo seochat tools logo