Go Premium for a chance to win a PS4. Enter to Win

x
?
Solved

add text file to int?

Posted on 2011-02-20
5
Medium Priority
?
851 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 400 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 30

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 86

Assisted Solution

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

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 30

Accepted Solution

by:
anarki_jimbel earned 1200 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

Configuration Guide and Best Practices

Read the guide to learn how to orchestrate Data ONTAP, create application-consistent backups and enable fast recovery from NetApp storage snapshots. Version 9.5 also contains performance and scalability enhancements to meet the needs of the largest enterprise environments.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Update (December 2011): Since this article was published, the things have changed for good for Android native developers. The Sequoyah Project (http://www.eclipse.org/sequoyah/) automates most of the tasks discussed in this article. You can even fin…
Hello there! As a developer I have modified and refactored the unit tests which was written by fellow developers in the past. On the course, I have gone through various misconceptions and technical challenges when it comes to implementation. I would…
The viewer will learn how to use NetBeans IDE 8.0 for Windows to connect to a MySQL database. Open Services Panel: Create a new connection using New Connection Wizard: Create a test database called eetutorial: Create a new test tabel called ee…
THe viewer will learn how to use NetBeans IDE 8.0 for Windows to perform CRUD operations on a MySql database.
Suggested Courses

926 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