Reputation: 1021
How to read an array of numbers from a file? I mean, how to read chars from a file?
Update: 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.
Upvotes: 0
Views: 1473
Reputation: 838106
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
.
Upvotes: 1
Reputation: 1038730
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();
Upvotes: 3