basic file I/O issue

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • xontrn@yahoo.com

    basic file I/O issue

    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.t xt");

    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

    #2
    Re: basic file I/O issue

    xontrn@yahoo.co m wrote:
    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.t xt");
    >
    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.Re ad() 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.T oString() to convert the
    string to an int. Clear out the StringBuilder and continue, until
    you've read all the data you want to.

    Pete

    Comment

    • Hilton

      #3
      Re: basic file I/O issue

      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]);
      }
      }


      <xontrn@yahoo.c omwrote in message
      news:1192670664 .104962.47200@k 35g2000prh.goog legroups.com...
      >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.t xt");
      >
      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?
      >

      Comment

      Working...