Solved

Reading a 2d array from a text file using c#

Posted on 2004-10-12
3
3,329 Views
Last Modified: 2010-08-05
I have a two dimensional array contained within a text file, which has undefined dimensions in terms of rows and columns.
example
12.333 322.222 22.23
344.52 22.3 2334.2
333.22 3342.3 33.4
I wish to read in the matrix contained in the text file into a two-dimensional array in c#. How is this achieved and implemented?
0
Comment
Question by:gxp071
[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
  • 2
3 Comments
 
LVL 8

Accepted Solution

by:
Razzie_ earned 500 total points
ID: 12288477
First read read through the entire file and count the number of lines. Also count the number of columns (seperated by a space). This code will work:

----------------------------------------------------------------------

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++;
}
------------------------------------------------------------------------------------

HTH,

Razzie
0
 
LVL 6

Author Comment

by:gxp071
ID: 12289224
Thanks for the help..!!
0
 
LVL 8

Expert Comment

by:Razzie_
ID: 12289855
No problem, glad I could help.
0

Featured Post

Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

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

Suggested Solutions

This article describes a simple method to resize a control at runtime.  It includes ready-to-use source code and a complete sample demonstration application.  We'll also talk about C# Extension Methods. Introduction In one of my applicationsā€¦
It was really hard time for me to get the understanding of Delegates in C#. I went through many websites and articles but I found them very clumsy. After going through those sites, I noted down the points in a easy way so here I am sharing that undeā€¦

751 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