• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 374
  • Last Modified:

Reading in data from a file C#

if i have a file such as:
in.txt
6 1 2 3 4 5 6
9 1 2 3 4 5 6 7 8 9
5 1 2 3 4 5
7 1 2 3 4 5 6 7

where the first number listed tells how many numbers are after it.  How do i write code so that i can read that in.  Normally i would do:

public static void ReadData()
            {
                  string fileName = "in.txt";

                  StreamReader fileReader = new StreamReader(fileName);

                  string sLine;

                  sLine = fileReader.ReadLine();

                  string[] split;
                  char delm = ' ';

                  while(sLine != null)
                  {
                        split = sLine.Split(delm);

      
                        
                        sLine = fileReader.ReadLine();
                  }
0
jmkotman
Asked:
jmkotman
1 Solution
 
nayernaguibCommented:
This will store and print the contents of each line in a string array. If you don't need the first element, you can simply skip it while processing the array.

public static void ReadData()
{
      string fileName = "in.txt";
      StreamReader fileReader = new StreamReader(fileName);
      string sLine;
      string[] values;

      sLine = fileReader.ReadLine();
      char delm = ' ';

      while(sLine != null)
      {
            values = sLine.Split(delm);
            for(int i=0; i<values.Length; i++)
                  Console.Write(values[i]+" ");
            Console.WriteLine();
                   
            sLine = fileReader.ReadLine();
      }
}

_______________

  Nayer Naguib
0
 
AlexNekCommented:
I like solution with split but if you need to use an other one, then scan the sting yourself.
Hint -  sLine[i] but don't forget to check if the string lenght is enough for number count
0

Featured Post

What does it mean to be "Always On"?

Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now