Solved

add text file to int?

Posted on 2011-02-20
5
844 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 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 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 100 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 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

Stressed Out?

Watch some penguins on the livecam!

Question has a verified solution.

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

Many of us here at EE write code. Many of us write exceptional code; just as many of us write exception-prone code. As we all should know, exceptions are a mechanism for handling errors which are typically out of our control. From database errors, t…
More often than not, we developers are confronted with a need: a need to make some kind of magic happen via code. Whether it is for a client, for the boss, or for our own personal projects, the need must be satisfied. Most of the time, the Framework…
This tutorial covers a step-by-step guide to install VisualVM launcher in eclipse.
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…

617 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