Celebrate National IT Professionals Day with 3 months of free Premium Membership. Use Code ITDAY17

x
?
Solved

add text file to int?

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

On Demand Webinar: Networking for the Cloud Era

Ready to improve network connectivity? Watch this webinar to learn how SD-WANs and a one-click instant connect tool can boost provisions, deployment, and management of your cloud connection.

Question has a verified solution.

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

Wouldn’t it be nice if you could test whether an element is contained in an array by using a Contains method just like the one available on List objects? Wouldn’t it be good if you could write code like this? (CODE) In .NET 3.5, this is possible…
Entity Framework is a powerful tool to help you interact with the DataBase but still doesn't help much when we have a Stored Procedure that returns more than one resultset. The solution takes some of out-of-the-box thinking; read on!
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 and create keystrokes in Netbeans IDE 8.0 for Windows.

730 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