Reputation: 4674
This is a beginner C++ homework problem, I know about vector, but it is not allowed to use in this assigment. I searched around and I found how to make an array[]
of unknown size too. But it is slightly trickly (sort of). The example I read are all along the lines of: get an input, then create the array base on that input (size n).
I have created this student class, but now I need an array
to store them. I do not know in advance how many students there are going to be. I only have an input of text file with each student on one line. The format is below, the sample is about 5, but I don't know how many the teacher will use to test my program.
Input file like this:
George Chan Computer_Science New York 23
Johnny Chan Computer_Science New Jersery 22
....
But the problem is I don't know how many students are there until I finish reading the whole text tile (or I don't know if there are other way to do it). My current approach is to read it line by line, increment a counter studentCounter
, until I finish, then I create my Student* myRoster = Student[studentCounter]
. But then when I have to start reading the file again. And go line by line to parse the information and create a Student
object and let a myRoster[x]
points to it. I feel like I am sort of doing the work twice just to have the right size. Are there some tricks or things I am missing?
Thank you.
Upvotes: 0
Views: 2217
Reputation: 64308
Here is one simple approach using recursion:
Student* readStudents(istream& infile,int& n_students)
{
string line = readLine(infile);
if (!infile) {
return new Student[n_students];
}
int index = n_students++;
Student* students = readStudents(infile,n_students);
students[index] = parseLine(line);
return students;
}
Then you call it like this:
int n_students = 0;
Student* students = readStudents(infile,n_students);
The idea is just to read the lines as you are going deeper into the recursion. By the time you hit the end of the file, you know how many students to allocate, and then you can parse the lines and fill the array in reverse order as you come out of the recursion. You'll also get the count of students returned through the output parameter.
Upvotes: 4
Reputation: 59987
Is the input file something that you define or is it defined for the exercise?
If you are defining the structure of the file you have two choices. You could either
a) Make the fields dixed length then just get the file size are the start and do a division to get the number of items.
or
b) First line stores the number of items in the file.
Upvotes: 0
Reputation: 490048
If you're ambitious enough, you can do roughly the same thing as vector
does -- allocate some space, keep track of how much of that space you're using, and when/if it gets full, allocate a bigger chunk (something like 1 1/2 or 2 times as big), copy the data from the previous block to the new one, and start inserting the new data into the new block. Repeat as necessary.
Upvotes: 1