Solved

add text file to int?

Posted on 2011-02-20
5
826 Views
Last Modified: 2013-12-17
Hi Experts,

I have this int:
            int[][] s =
        {

            new[] { 1, 4 },
            new[] { 1, 3},
 
        };

As you can see I have to specify the int elements, but I want to read a text file and add their lines as elements in that int. The text I have looks like this:
data.txt:
1,4
1,3

I would like to read the data.txt file and add their lines to ( int[][] s)?
Note: I am using C# 2008

Thanks for your help
Regards
Sat80
0
Comment
Question by:Sat80
  • 3
5 Comments
 
LVL 9

Assisted Solution

by:s_chilkury
s_chilkury earned 100 total points
ID: 34940030
First read read through the entire file and count the number of lines. Also count the number of columns (seperated by a comma).
String[,] array2D;

int numberOfLines = 0, numberOfColumns = 0;
string line;
System.IO.StreamReader sr = new System.IO.StreamReader(filename);
                  
while((line = sr.ReadLine()) != null)
{
      numberOfColumns = line.Split(',').Length;
      numberOfLines++;
}
sr.Close();

array2D = new String[numberOfLines,numberOfColumns];
numberOfLines = 0;
                  
sr = new System.IO.StreamReader(filename);
while((line = sr.ReadLine()) != null)
{
      String[] tempArray = line.Split(',');
      for(int i=0;i<tempArray.Length;++i)
      {
            array2D[numberOfLines, i] = tempArray[i];
      }
      numberOfLines++;
}

Open in new window

0
 
LVL 29

Expert Comment

by:anarki_jimbel
ID: 34940102
OK, here is my solution. I suggest that all lines in the text file have two entries only. At least - same number of entries. Otherwise everything will be a bit more complicated. Have a look:

using System.IO;// don't forget the line


        private void button2_Click(object sender, EventArgs e)
        {

            try
            {
                // Create an instance of StreamReader to read from a file.
                // The using statement also closes the StreamReader.
                using (StreamReader sr = new StreamReader("TextFile1.txt"))
                {

                    List<int[]> listOfArrays = new List<int[]>();
                    String line;
                    // Read and display lines from the file until the end of
                    // the file is reached.
                    while ((line = sr.ReadLine()) != null)
                    {
                        string[] sar = line.Split(new string[] { ",", " " }, StringSplitOptions.RemoveEmptyEntries);
                        int[] intArr = new int[2];
                        // if we have only 2 elements - can do like :
                        intArr[0] = int.Parse(sar[0]);
                        intArr[1] = int.Parse(sar[1]);
                        listOfArrays.Add(intArr);
                    }
                    int[][] intArrayOfArrays = listOfArrays.ToArray();

                    for (int i = 0; i < intArrayOfArrays.Length; i++)
                    {
                        int[] intAr = intArrayOfArrays[i];
                        for (int j = 0; j < intAr.Length; j++)
                        {
                            System.Diagnostics.Debug.Write(intAr[j].ToString() + " - ");
                        }
                        System.Diagnostics.Debug.WriteLine("");

                    }
                }
            }

Open in new window

0
 
LVL 85

Assisted Solution

by:Mike Tomlinson
Mike Tomlinson earned 100 total points
ID: 34940110
Instead of List<int[]>, you could just use List<List<int>>, a List of Lists.
0
 
LVL 29

Expert Comment

by:anarki_jimbel
ID: 34940118
Just a note:

The asker wanted this type of an array:

 int[][] s

Really, this is an array of arrays. For integers, BTW.


s_chilkury proposes to use two-dimensional String[,] array2D; (of strings!). It's a bit different..

And yes, I put some parsing in my code but didn't much care about error handling. really, I always use

int.TryParse method...instead of just Parse...

0
 
LVL 29

Accepted Solution

by:
anarki_jimbel earned 300 total points
ID: 34940143
Idle_Mind is right as always :)

Variation:
private void button2_Click(object sender, EventArgs e)
        {

            try
            {
                // Create an instance of StreamReader to read from a file.
                // The using statement also closes the StreamReader.
                using (StreamReader sr = new StreamReader("TextFile1.txt"))
                {

                    List<List<int>> listOfLists = new List<List<int>>();
                    String line;
                    // Read and display lines from the file until the end of
                    // the file is reached.
                    while ((line = sr.ReadLine()) != null)
                    {
                        string[] sar = line.Split(new string[] { ",", " " }, StringSplitOptions.RemoveEmptyEntries);   
                        // make a list
                        List<int> lst = new List<int>();
                        foreach (string s in sar)
                        {
                            lst.Add(int.Parse(s));
                        }
                        listOfLists.Add(lst);
                    }

                    foreach (List<int> lst in listOfLists)
                    {
                        foreach (int i in lst)
                        {
                            System.Diagnostics.Debug.Write(i.ToString() + " - ");
                        }
                        System.Diagnostics.Debug.WriteLine("");

                    }
                }
            }

Open in new window

0

Featured Post

Highfive + Dolby Voice = No More Audio Complaints!

Poor audio quality is one of the top reasons people don’t use video conferencing. Get the crispest, clearest audio powered by Dolby Voice in every meeting. Highfive and Dolby Voice deliver the best video conferencing and audio experience for every meeting and every room.

Join & Write a Comment

A long time ago (May 2011), I have written an article showing you how to create a DLL using Visual Studio 2005 to be hosted in SQL Server 2005. That was valid at that time and it is still valid if you are still using these versions. You can still re…
Exception Handling is in the core of any application that is able to dignify its name. In this article, I'll guide you through the process of writing a DRY (Don't Repeat Yourself) Exception Handling mechanism, using Aspect Oriented Programming.
This tutorial covers a step-by-step guide to install VisualVM launcher in eclipse.
The viewer will learn how to synchronize PHP projects with a remote server in NetBeans IDE 8.0 for Windows.

746 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

12 Experts available now in Live!

Get 1:1 Help Now