1,105,625 Community Members

c# file reading problem with 2-d arrays

Member Avatar
mIND.dEcEpToR
Newbie Poster
7 posts since Sep 2012
Reputation Points: 0 [?]
Q&As Helped to Solve: 0 [?]
Skill Endorsements: 0 [?]
 
0
 

this is how my data in txt file:

1--2--3--
3-4-4-5--
-7-3-4---
7--5--3-6
--7---4--
3-2--4-5-
------3--
2-6--7---
4---4--3-

is my c# code to do file reading with the display too:

public void populate_grid_by_file()
        {
            int counter = 0;
            string line;

            // Read the file and display it line by line.
            System.IO.StreamReader file =
               new System.IO.StreamReader("data.txt");
            for (int i = 0; i < Sodoku_Gri.GetLength(0); i++)
            {
                while ((line = file.ReadLine()) != null)
                {
                    for (int j = 0; j < Sodoku_Gri.GetLength(1); j++)
                    {
                        Console.Write(line[j].ToString());

                    }
                    Console.WriteLine(line);
                    counter++;
                }
            }
            file.Close();
            // Suspend the screen.
            Console.ReadLine();
        }

but when i display my array with the file reading above it is like:

1--2--3--1--2--3--
3-4-4-5--3-4-4-5--
-7-3-4----7-3-4---
7--5--3-67--5--3-6
--7---4----7---4--
3-2--4-5-3-2--4-5-
------3--------3--
2-6--7---2-6--7---
4---4--3-4---4--3-

cnt understand why duplication! help!

Member Avatar
tinstaafl
Postaholic
2,012 posts since Jun 2010
Reputation Points: 559 [?]
Q&As Helped to Solve: 403 [?]
Skill Endorsements: 35 [?]
 
1
 

You seem to have an extra console.writeline statement that's printing 'line' an extra time. Also you're printing to the console for every increment of j. If 'Sodoku_Gri.GetLength(1)' equals 2 then each line of the file will print 2 times. Can't see a reason for that loop to be in there. If you don't need it you could replace lines 13-19 with: Console.Write(line[j].ToString() + \n); . You might want to consider copying that file right into an array(StringArray[]=System.IO.File.ReadAllLines(path)), 1 line per element, then it's a simple matter of looping through the array to print each line.

You
This article has been dead for over three months: Start a new discussion instead
Post:
Start New Discussion
View similar articles that have also been tagged: