Thursday, April 12, 2012

Array of unknown size base on the input file

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.

1 comment:

  1. 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.