Question

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.

Was it helpful?

Solution

Try Splitting the line by spaces

string [] numbers = file.ReadLine().Split(new char[]{' '},
                                       StringSplitOptions.RemoveEmptyEntries);

OTHER TIPS

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.

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));
    }

You can use File.ReadAllText method:

var numbers = File.ReadAllText("C:\\text.txt")
             .Split()
             .Where(x => x.All(char.IsDigit))
             .Select(int.Parse)
             .ToList();
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top