structs and arrays
in my program i have a struct called Packages which contains the members weight, length, width and depth. This data is in a file whose first line is the number of packages, and then the lines after are the package information, each package having its own line. I have to use one function to read in the number of packages, allocate the correct number of Package struct elements in the array and then have a loop which calls another function that is used to get the information for a single package, so it loops untill i have each package in the array. I am very confused on how to do this.
Here is an example of how I addressed using an array of structs awhile back.. this is very similar to what you want to do. Take a look and see if you can get the jist of what is going on. :)
I can't really make the connection between that example and the one im am faced with. I have a function getPkgs that first gets the number of packages from the first line of the data file. next this function contains a for loop that will call a second function inPack that will get the data for a single package each time the loop goes through until all the packages are inputted. Im not sure how to write the second function or how to get the information from the file into the array. I have and array packList and a struct
If you can help me get this sorted out I'd appreciate it
If you already have a function that gets the number of packages from your file, what's the difference between getting that value and getting these other values? You're just reading in floats this time instead of what was most likely an integer value.
Is this a binary file or text file?
Assuming text data (whitespace delimited), you can use the stream extractor operator >> just like you might have (probably?) used to get the first value (the count). It sounds, based on your description of how you want the second function to work, that the function probably just needs a single line of code similar to:
If binary data you're going to need to use the stream's read member function.
name_of_input_stream >> whatever.weight >> whatever.length >> whatever.width >> whatever.depth;
You are probably going to need to pass in the stream object (by reference) as an argument to the function, unless your stream object happens to be global (which it should not be); you're also going to need to pass the array element to be filled, a pointer/reference to a single Package element and what I have refered to as whatever in the above sample.
Here are a couple of tips:
1) in the main body of your program, instantiate an array of stuct objects
2) your void inPack(Packages& myPackages, int current_index); function will probaby exhibit this type of behavior:
cout << "Enter weight: ";
cin >> myPackages[current_index].weight;
cout << "Enter Length: ";
cin >> myPackages[current_index].length;
edit: ^^^^^ what hk_mp5kpdw said is probably a more efficient method :) ^^^^^^^
thanks for the help i think i got it now :)