Link to home
Start Free TrialLog in
Avatar of cotj73
cotj73Flag for United States of America

asked on

Input text file to an array

I am attempting to read a file in, and throw the contents into a matrix, where each element is stored in a different container
Example
Text File
123
456
789

Matrix
{{1,2,3}
 {4,5,6}
 {7,8,9}}

I am using stream reader to read the contents in, and know how to pull the contents into an array, but not a Matrix
Avatar of Ravi Vaddadi
Ravi Vaddadi
Flag of United States of America image

Matrix is just a multi-dimensional array. If you could pull the contents into an array then same logic could be used to pull it into a multi-dimensional array.

If you still have an issue please elaborate.
Avatar of Vel Eous
Vel Eous

If you are referring how to convert a string to an array:


string str = "abcde123";
char[] charArray = s.ToCharArray();
ASKER CERTIFIED SOLUTION
Avatar of cotj73
cotj73
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Honestly, I don't quite like your solution. One problem I can see is in the last statement:

CharMap[i] = saTemp[i].Split(' ');

In your file
123
456
789
Digits are NOT separated with spaces - so it won't work.
So the solution does not satisfy your requirements.

I can suggest another solution. It's not shorter really:
        private void button1_Click(object sender, EventArgs e)
        {
                string[][] CharMap;
                List<string> lines = new List<string>();
                using (StreamReader sr = new StreamReader("text.txt"))
                {
                    String line;
                    // Read and display lines from the file until the end of the file is reached.
                    while ((line = sr.ReadLine()) != null)
                    {
                        lines.Add(line);
                    }
                }
                CharMap = new String[lines.Count][];
                for (int firstIndex = 0; firstIndex < lines.Count; firstIndex++)
                {
                    CharMap[firstIndex] = new string[lines[firstIndex].Length];
                    for (int secondIndex = 0; secondIndex < lines[firstIndex].Length; secondIndex++)
                    {
                        CharMap[firstIndex][secondIndex] = lines[firstIndex].Substring(secondIndex, 1);
                    }
                }
                // display result in output window
                for (int firstIndex = 0; firstIndex < CharMap.Length; firstIndex++)
                {
                    for (int secondIndex = 0; secondIndex < CharMap[firstIndex].Length; secondIndex++)
                    {
                        System.Diagnostics.Debug.Write(CharMap[firstIndex][secondIndex]);
                    }
                    System.Diagnostics.Debug.WriteLine("");
                }
        }

Open in new window