basic file I/O issue

  • Thread starter Thread starter xontrn
  • Start date Start date
X

xontrn

I have a text file that is just a list of integers separated by a
space. In C++ I could do something like:

ifstream fin("filename.txt");

int x, y, z;
fin >> x >> y >> z;

to read the integers in.

How do I do that in C# with .NET IO?

Do I have to just read it all in as a giant string and then parse the
string?
 
I have a text file that is just a list of integers separated by a
space. In C++ I could do something like:

ifstream fin("filename.txt");

int x, y, z;
fin >> x >> y >> z;

to read the integers in.

How do I do that in C# with .NET IO?

Do I have to just read it all in as a giant string and then parse the
string?

I'm not aware of anything in C# like the C++ standard i/o stuff.
However, you definitely don't have to read everything in "as a giant
string". You can use StreamReader to open the file, and then use the
StreamReader.Read() method to read the characters from the file.

The easiest thing to code would be to just read a single character at a
time, adding it iteratively to a StringBuilder instance. Then when you
hit a space, call int.Parse(), int.TryParse(), or Convert.ToInt32()
passing the result of calling StringBuilder.ToString() to convert the
string to an int. Clear out the StringBuilder and continue, until
you've read all the data you want to.

Pete
 
Not the most efficient, and it assumes (at least) three integers per line.
Add the necessary error checking and performance improvements as required.


using System.IO;

using (StreamReader sr = new StreamReader ("filename.txt"))
{
string line;
while ((line = sr.ReadLine()) != null)
{
string[] tokens = line.Split (' ');

int a = int.Parse (tokens [0]);
int b = int.Parse (tokens [1]);
int c = int.Parse (tokens [2]);
}
}
 

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