1

I am reasonably new to C# programming I took it up in the past week and I am having issues connecting two parts of my program together. Where I stand I have it reading information from a text file and then I need to pass the information into ints for the main part of the program to use and run its functions with. Basically the text file will look something like this

30 3 5

100 7 16

etc.... each set of numbers is in groups of 3s just to clarify if I didn't explain it well enough.

but with each group of numbers I need them set up where I can pass to my ints X Y and Z that are declared after the text file is ran so if needed. The only thought that I have had at the moment is pass them into an array and call the ints (I can do int x = arr[1]; if I coded that right) that way but I have had no luck getting them into the array let alone calling them individually.

I am more then open to hearing other options but could someone please help and explain how it is done in the sections of code I would like to understand what is happening at each step.

3
  • 6
    edit and add code you've come so far Commented Dec 26, 2014 at 19:02
  • I would use a List<int> for each row, then add those rows to a List<List<int>>. You'll have to parse each row and convert the string values into int before adding them to the list. Commented Dec 26, 2014 at 19:10
  • 1
    Idle is right: The word is parse! You can ReadAllLines and the Split(' ').. Commented Dec 26, 2014 at 19:37

2 Answers 2

1

You can do this way. However you need to work on it to make more suitable according to your needs: I can admit that you need to do more error handling in my below code e.g in Convert.ToInt32section

           public void XYZFile()
           {
                List<XYZ> xyzList = new List<XYZ>();
                string[] xyzFileContant = File.ReadAllLines(Server.MapPath("~/XYZ.txt"));
                //int lineCount = xyzFileContant.Length;
                foreach (string cont in xyzFileContant)
                {
                    if (!String.IsNullOrWhiteSpace(cont))
                    {
                        string[] contSplit = cont.Split(new string[] { " " }, StringSplitOptions.RemoveEmptyEntries);
                        xyzList.Add(new XYZ
                                            {
                                                X = Convert.ToInt32(contSplit[0]),
                                                Y = Convert.ToInt32(contSplit[1]),
                                                Z = Convert.ToInt32(contSplit[2])
                                            }
                            );
                    }
                }
            }



    public class XYZ
    {
        public int X { get; set; }
        public int Y { get; set; }
        public int Z { get; set; }
    }

So, let me know if that helps you.

Sign up to request clarification or add additional context in comments.

6 Comments

I just want to ask some qestions on specific lines since I haven't seen some of these before. List<XYZ> xyzList = new List<XYZ>(); - is this line creating a list? cont - is this continue or count? I haven't seen this used before either string[] contSplit = cont.Split(new string[] { " " }, StringSplitOptions.RemoveEmptyEntries); this looks like it is creating an array named string and removing all spaces from the entries is that correct? X = Convert.ToInt32(contSplit[0]), - is this splitting the array and assigning a value to x after converting it to an int?
public int X { get; set; } - is this line allowing me to grab x and use it further into the program?
List<XYZ> is collection of XYZ class and XYZ class has member X, Y and Z to hold said value say X=30, Y=3, Z=5. cont is just a string type variable. string[] contSplit = cont.Split(new string[] { " " }, StringSplitOptions.RemoveEmptyEntries);-> Yes I am splitting each line of the text file and storing it in string array. so it will have values like contSplit[0] = "30",contSplit[1]="3" and contSplit[2]="5"
Thank you for all of the help the code defiantly makes more sense now and it should help me finish my project.
@Mad Hatter Was this a real question or a request to solve your homework? (just curious)
|
0

try this:

static int[] parse(string st)//let st be "13 12 20"
{
    int[] a = new int[3];
    a[0] = int.Parse(st.Substring(0, st.IndexOf(' ')));//this will return 13, indexof means where is the space, substring take a portion from the sting
    st = st.Remove(0, st.IndexOf(' ') + 1);//now remove the first number so we can get the second, st will be "12 20"
    a[1] = int.Parse(st.Substring(0, st.IndexOf(' ')));//second number
    st = st.Remove(0, st.IndexOf(' ') + 1);//st="20"
    a[2] = int.Parse(st);//all we have is the last number so all string is needed(no substring)
    return a;
}

this method parse the string and get three ints from it and stores them in an array, then return this array. we shall use it to parse the lines of the text file like this:

static void Main(string[] args)
{
    StreamReader f = new StreamReader("test.txt");//the file
    int x, y, z;
    while (!f.EndOfStream)//stop when we reach the end of the file
    {
        int[] a = parse(f.ReadLine());//read a line from the text file and parse it to an integer array(using parse which we defined)
        x = a[0];//get x
        y = a[1];//get y
        z = a[2];//get z
        //do what you want with x and y and z here I'll just print them
        Console.WriteLine("{0} {1} {2}", x, y, z);
    }
    f.Close();          //close the file when finished  
}   

8 Comments

Is the first part of this reading the text file and pasting it into an array while setting x y and z? and for the second part I am not really sure what all of that does would you mind explain it?
I've edited my answer, if you have any questions, I'll answer them
I have read though the code and ran it but I get an error when I try to run it. I want to understand both aspects of it but I get really cloudy when I reach the a[0] = int.Parse(st.Substring(0, st.IndexOf(' '))); section of the code. This is the error that is returned by the way. An unhandled exception of type 'System.ArgumentOutOfRangeException' occurred in mscorlib.dll Additional information: Length cannot be less than zero.
@MadHatter are there long integers in your text file ? a long won't parse by int.parse but by long.parse , if you have that I'll edit my answer. ofcourse long means numbers bigger than 2^32 -1 or smaller than -2^32
The longest ints that I had set up for the tests were no more then 3 digits and the most I believe that are going to be tested are 4 digits and my first test run to see if I got the code working correctly was using the 13 12 20 starting like that then I swapped them to each their own line
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.