I don't have idea how make functional program and I wanna transfer text file into 2D array.
Thank you for answers
This is content of my text file:
0000000011
0011100000
0000001110
1000011100
1000000000
0000111111
1000001100
1000000000
1000011000
1000001111
Code:
static void Main(string[] args)
{
int[,] map = new int[10, 10];
StreamReader reader = new StreamReader(@"Lode.txt");
for (int i = 0; i < 10; i++)
{
for (int j = 0; j < 10; j++)
{
**WHAT I SHOULD PUT HERE**
}
}
reader.Close();
}
You should do following (code with my comments):
var map = new int[10, 10];
using (var reader = new StreamReader("Lode.txt")) // using will call close automatically
{
for (var i = 0; i < 10; i++)
{
var line = reader.ReadLine(); // read one line from file
for (var j = 0; j < 10; j++)
{
map[i, j] = Int32.Parse(line[j].ToString()); // get one symbol from current line and convert it to int
}
}
}
You can try with a little LINQ as follows:
static void Main(string[] args)
{
string filePath = @"Lode.txt";
// Read file contents and store it into a local variable
string fileContents = File.ReadAllText(filePath);
/* Split by CR-LF in a windows system,
then convert it into a list of chars
and then finally do a int.Parse on them
*/
int[][] map = fileContents.Split('\r', '\n')
.Select(x => x.ToList())
.Select(x => x.Select(y => int.Parse(new string(y, 1))).ToArray())
.ToArray();
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.