I am looking to read numbers from the text file and load them into an array in order to load a save game.
This is my ReadFile Function
public String ReadFile()
{
string readText;
string fullFileName = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "SaveGame.txt");
try
{
using (var reader = new StreamReader(fullFileName))
{
readText = reader.ReadLine();
Debug.Write(readText);
}
}
catch
{
readText = "Couldn't read that file.";
}
return readText;
}
This is my output
Row: 0 Col 0 0
Row: 1 Col 0 0
Row: 2 Col 0 0
Row: 3 Col 0 0
Row: 4 Col 0 0
Row: 5 Col 0 0
Row: 6 Col 0 0
Row: 0 Col 1 0
Row: 1 Col 1 0
Row: 2 Col 1 0
Row: 3 Col 1 0
Row: 4 Col 1 0
Row: 5 Col 1 0
Row: 6 Col 1 0
Row: 0 Col 2 0
Row: 1 Col 2 0
Row: 2 Col 2 0
Row: 3 Col 2 0
Row: 4 Col 2 0
Row: 5 Col 2 0
Row: 6 Col 2 0
Row: 0 Col 3 0
Row: 1 Col 3 0
Row: 2 Col 3 0
Row: 3 Col 3 0
Row: 4 Col 3 0
Row: 5 Col 3 2
Row: 6 Col 3 0
Row: 0 Col 4 0
Row: 1 Col 4 0
Row: 2 Col 4 0
Row: 3 Col 4 0
Row: 4 Col 4 0
Row: 5 Col 4 0
Row: 6 Col 4 0
Row: 0 Col 5 0
Row: 1 Col 5 0
Row: 2 Col 5 0
Row: 3 Col 5 0
Row: 4 Col 5 0
Row: 5 Col 5 0
Row: 6 Col 5 0
Row: 0 Col 6 0
Row: 1 Col 6 0
Row: 2 Col 6 0
Row: 3 Col 6 0
Row: 4 Col 6 0
Row: 5 Col 6 0
Row: 6 Col 6 0
I want to read the 3 numbers per line and load them into an array like so
if(array[num1][num2] == num3)
{
// Action
}
num1 being the first number on a line, num2 being the second and num3 being the third and then doing this for each line.
CodePudding user response:
Do the numbers stay under 10? If so you can just remove all the text from the readText with a regex, example:
string numberOnly = Regex.Replace(readText, "[^0-9,-] ", "")
And then just take [0] , [1] [2] and you have your seperate numbers.
This only works if your number stays below 10 though! Which looks like it in your example, but I don't have much context.
CodePudding user response:
You can use a helper function to extract all the numbers from a line:
void Main()
{
string fullFileName = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "SaveGame.txt");
var lines = File.ReadAllLines(fullFileName);
foreach(var numbers in lines.Select(l => ParseInts(l, 3)))
Console.WriteLine(numbers);
}
public static int[] ParseInts(string str, int? count = null)
{
var regex = new Regex(@"([- ]?[0-9] )");
var matches = regex.Matches(str);
if (count != null)
Debug.Assert(matches.Count == count);
return matches.Select(match => int.Parse(match.Value)).ToArray();
}
