![]() |
|
C# reading text into 2D array |
Jeffsg605
Member #13,048
July 2011
|
Sorry to post an XNA question here but I can't find the answer to this anywhere including XNA and C# forums. Does anybody know how to read a text file into a 2D array in C#. I have this: int[,] map; FileStream fileStream = new FileStream(@"Map.txt", FileMode.Open); map = new int[5,5]; for (int i = 0; i < 5; i++) { for (int j = 0; j < 5; j++) { map[i,j] = // what goes here? } }
Any direction is much appreciated. |
james_lohr
Member #1,947
February 2002
|
What are you trying to read from your file? - if it is simply an array of chars: 1var width = 5;
2var height = 5;
3var map = new char[width,height];
4var file = new StreamReader("Map.txt");
5string line;
6var lineCount = 0;
7while((line = file.ReadLine()) != null)
8{
9 if(lineCount<height){
10 for(int i=0;i<width && i < line.Length){
11 map[i,lineCount] = line[i];
12 }
13 }
14 lineCount++;
15}
16
17file.Close();
If it is an array of integers, then you will need to split it by some separator per line, and parse the individual integers.
|
bamccaig
Member #7,536
July 2006
![]() |
Show us an example file. -- acc.js | al4anim - Allegro 4 Animation library | Allegro 5 VS/NuGet Guide | Allegro.cc Mockup | Allegro.cc <code> Tag | Allegro 4 Timer Example (w/ Semaphores) | Allegro 5 "Winpkg" (MSVC readme) | Bambot | Blog | C++ STL Container Flowchart | Castopulence Software | Check Return Values | Derail? | Is This A Discussion? Flow Chart | Filesystem Hierarchy Standard | Clean Code Talks - Global State and Singletons | How To Use Header Files | GNU/Linux (Debian, Fedora, Gentoo) | rot (rot13, rot47, rotN) | Streaming |
Jeffsg605
Member #13,048
July 2011
|
Actually yeah, an array of chars was fine. I was focusing on reading ints and having a lot of trouble but chars did the job just fine. It was a lot of unnecessary frustration. Thanks guys! |
|