954,514 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

Read rows/columns of numbers in a text file

I have a text file with the following numbers:

1 2 3
4 5 6

How do I read each individual number into an array?

It needs to move along each row so read in 1, 2 and then 3 into a array of 6 integers.
Then move to the second row and read 4 5 and 6...


Thank You

junioryz
Newbie Poster
8 posts since Sep 2009
Reputation Points: 10
Solved Threads: 0
 

If your file is in the above mentioned format, then you can write the code something like this:

internal int[] loadArray(string path)
        {

            StreamReader sr = new StreamReader(path);
            int[] num=new int[0];

            try
            {
                while (!sr.EndOfStream)
                {
                    string[] temp = sr.ReadToEnd().Replace('\n',' ').Split(' ');
                    num = new int[temp.Length];

                    for (int i = 0; i < temp.Length; i++)
                    {
                        if (!int.TryParse(temp[i], out num[i]))
                        {
                            throw new InvalidDataException();
                        }
                    }
                }

                return num;

            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                sr.Close();
            }

        }
Knvn
Junior Poster in Training
86 posts since Feb 2011
Reputation Points: 24
Solved Threads: 12
 

I did two examples for you, one is to use string array the other is to use char (which I prefer most in this case):

private void ReadingFile()
        {
            List<string> list = new List<string>();
            string path = @"C:\1\test11.txt";
            string[] lines = System.IO.File.ReadAllLines(path);

            //1. option:
            for (int i = 0; i < lines.Length; i++)
            {
                string[] line = lines[i].Split(' ');
                for (int j = 0; j < line.Length; j++)
                    list.Add(line[j]);
            }

            //2. option:
            List<string> list2 = new List<string>();
            for (int i = 0; i < lines.Length; i++)
            {
                char[] chars = lines[i].ToCharArray();
                for (int j = 0; j < chars.Length; j++)
                {
                    if (!Char.IsWhiteSpace(chars[j]))
                        list2.Add(chars[j].ToString());
                }
            }
        }


Hope it helps,
Mitja

Mitja Bonca
Nearly a Posting Maven
2,485 posts since May 2009
Reputation Points: 641
Solved Threads: 474
 

This article has been dead for over three months

Post: Markdown Syntax: Formatting Help
You
View similar articles that have also been tagged: