How to read from a file array of numbers? I mean, how to read chars from a file?
sorry for bad eng.
upd: yes, i can :) just: "1 2 3 4 5 6 7 8" and etc. I just do not know how to read chars from a file.
How to read from a file array of numbers? I mean, how to read chars from a file?
sorry for bad eng.
upd: yes, i can :) just: "1 2 3 4 5 6 7 8" and etc. I just do not know how to read chars from a file.
If your file is not too large you can read it all into memory using for example ReadAllLines
and then use TryParse to interpret the strings as integers. Here is some example code you could use as a starting point:
List<int> integers = new List<int>();
foreach (string line in File.ReadAllLines(path))
{
foreach (string item in line.Split(' '))
{
int i;
if (!int.TryParse(item, out i))
{
throw new Exception("Implement error handling here");
}
integers.Add(i);
}
}
If you know that the file will always contain valid input you can simplify this slightly by using Parse
instead of TryParse
.
string[] numbers = File.ReadAllText("yourfile.txt").Split(' ');
or you could convert these to integers:
int[] numbers = File
.ReadAllText("yourfile.txt")
.Split(' ')
.Select(int.Parse)
.ToArray();