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?
Peter Duniho - 18 Oct 2007 04:18 GMT
> I have a text file that is just a list of integers separated by a
> space. In C++ I could do something like:
[quoted text clipped - 10 lines]
> 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
Hilton - 18 Oct 2007 10:05 GMT
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]);
}
}
>I have a text file that is just a list of integers separated by a
> space. In C++ I could do something like:
[quoted text clipped - 10 lines]
> Do I have to just read it all in as a giant string and then parse the
> string?