Reputation: 133
I have an external text file which has numbers in it. like 4 54 12 32 separated by spaces. I want to be able to read all the numbers and add them to a list.
static void Main(string[] args)
{
List<int> numbers;
numbers = new List<int>();
StreamReader file = new StreamReader("C:\\text.txt");
while (!file.EndOfStream)
{
string line = file.ReadLine();
Console.Write(line + " ");
}
}
ReadLine reads the whole line so I cannot separate the individual numbers and convert them to ints and I have tried Read which reads the character code of each number rather than the number itself.
Upvotes: 0
Views: 1856
Reputation: 101691
You can use File.ReadAllText
method:
var numbers = File.ReadAllText("C:\\text.txt")
.Split()
.Where(x => x.All(char.IsDigit))
.Select(int.Parse)
.ToList();
Upvotes: 0
Reputation: 3060
This method should help you.
public static IEnumerable<int> ReadInts(string path)
{
var txt = File.ReadAllText(path);
return Regex.Split(txt, @"\s+").Select(x => int.Parse(x));
}
Upvotes: 0
Reputation: 26209
Try Splitting the line by spaces
string [] numbers = file.ReadLine().Split(new char[]{' '},
StringSplitOptions.RemoveEmptyEntries);
Upvotes: 1
Reputation: 1398
Split method of string object ( http://msdn.microsoft.com/fr-fr/library/System.String.Split%28v=vs.110%29.aspx ) is what you're looking for.
Upvotes: 0