Click here to Skip to main content
15,886,873 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have text file text.txt with values:
1 2 3
2 2 5
2 4 6
3 5 7
3 3 8
6 2 44

Each row need to put in one string


I have this code;

C#
StreamReader dFile = null;
           dFile = new StreamReader("Broj2.txt");
           char[] SPACE = new char[] {' ' };
          

           string a = dFile.ReadLine();
           string[] data = a.Split(SPACE); 


           int[] niz = new int[3];
           niz[0] = Convert.ToInt32(data[0]);
           niz[1] = Convert.ToInt32(data[1]);
           niz[2] = Convert.ToInt32(data[2]);

           while ( )
           {
               a = dFile.ReadLine();
               data = a.Split(SPACE);
           }



For each row should be put to one string, and a valuable asset that we read line by line using help while function.What goes into the bracket while?
Please help!
Posted
Comments
dax88 24-Nov-12 6:43am    
Don't work.He read only first 4 line, i have 15 line.
Philippe Mori 24-Nov-12 9:37am    
Your while should start be just after the first ReadLine and uses a != null as its condition and you should remove the last line in your while block since data is computed at the very beginning of the block (once you have moved the while)

You can try this...

C#
// Read each line of the file into a string array. Each element
// of the array is one line of the file.

string[] lines = System.IO.File.ReadAllLines("Broj2.txt");
int[] niz = new int[3];



foreach (string line in lines)
{

    string[] data = line.Split(' ');


    niz[0] = Convert.ToInt32(data[0]);
    niz[1] = Convert.ToInt32(data[1]);
    niz[2] = Convert.ToInt32(data[2]);

}
 
Share this answer
 
v2
Comments
Philippe Mori 24-Nov-12 9:34am    
Effectivelly the easiest way for usual files. If your file run into hundredths of mégabytes, then it might not be a good idea to read the whole file at once...
you can do something like below:

C#
while(dFile.ReadLine())
{
      a = dFile.ReadLine();
      data = a.Split(SPACE);
}
 
Share this answer
 
Comments
Philippe Mori 24-Nov-12 9:32am    
It won't properly work as it would skip half the lines. An easy way is to read once the line into a variable before entering the loop (which will test that variable) and update the variable just before the end of the statement block.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900