Parsing text files

  • Thread starter Thread starter Ron
  • Start date Start date
R

Ron

Hi,

I need to parse text (ie. created in Notepad) files for numbers (doubles).

In Borland C++ Builder the following works:

if(!InVect.is_open())
{
InVect.open(TxtFileName.c_str()) ;
}

for(int Index = 1; Index < ILayerSize; Index++)
{
InVect >> InputVect[Index] ;
etc
}

('InputVect' is an array of doubles.)

I have been trying to perform the same kind of operation in C# but without
success so far.

Any help much appreciated,
Ron.
 
Hi Ron,

Is the file ordered in any way, for instance only numbers separated with a
linebreak?
In that case you can simply read the whole file as a string, split the
string at each linebreak or other separator, and then convert all entries
in the resulting string to doubles.
 
Managed to do it this way but it seems a bit long winded:

if(openFileDialog1.ShowDialog() == DialogResult.OK)
{
string TrainFileName = openFileDialog1.FileName;
if (File.Exists(TrainFileName))
{
StreamReader s = new StreamReader(TrainFileName);
ArrayList strs = new ArrayList();
string temp = null;
string st = s.ReadToEnd();
int strInd = 0;
for (int i = 0; i < st.Length; i++)
{
if ((st >= '0' && st <= '9')
|| st == '.' || st == '+'
|| st == '-')
{
temp += st;
}
else
{
strs.Add(temp);
temp = null;
}

}
foreach(string a in strs)
{
double r;
if(double.TryParse(a,out r))
richTextBox1.Text += r.ToString() + '\n'; // These
values will be assigned to an array of doubles
}

s.Close();
}
}
 
Hello Ron,

Assuming you have a text file with one double per line you could do the following.

ArrayList nums = new ArrayList();
string filename = "";
if (File.Exists(filename))
{
using (TextReader tr = new StreamReader(filename))
{
string line;
while ((line = tr.ReadLine()) != null)
{
Double d;
if (Double.TryParse(line, out d))
nums.Add(d);
}
}
}

If you just have a text file with double delimited by white space perhaps using a regular expression to split them would be easist

if (File.Exists(filename))
{
using (TextReader tr = new StreamReader(filename))
{
string[] split = Regex.Split(tr.ReadToEnd(), @"(?m)\s+");

foreach (string num in split)
{
Double d;
if (Double.TryParse(num, out d))
nums.Add(d);
}
}
}

HTH
Wes Haggard
http://weblogs.asp.net/whaggard/
 
Thanks Wes,

The regular expression stuff is new to me.

Your routine looks ideal for my purposes - I'll give it a try!


Regards,
Ron.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Back
Top